Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ios - Convert NSDate to an Integer

So my dilemma is that I can't figure out how to store the date only in an integer value (fetched using:

NSDate* date = [NSDate date]

I found this code online which seems similar to what I need (I thought that changing setDateFormat to @"dd" would've worked (but apparently it didn't)

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy"];

//Optionally for time zone conversions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

NSString *stringFromDate = [formatter stringFromDate:date];

Am I just forgetting something simple about integers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Swift

NSDate to Int

// using current date and time as an example
let someNSDate = NSDate() 

// convert NSDate to NSTimeInterval (typealias for Double)
let timeInterval = someNSDate.timeIntervalSince1970

// convert to Integer
let myInt = Int(timeInterval)

Doing the Double to Int conversion causes the milliseconds to be lost. If you need the milliseconds then multiply by 1000 before converting to Int.

Int to NSDate

Including the reverse for completeness.

// convert Int to Double
let timeInterval = Double(myInt)

// create NSDate from Double (NSTimeInterval)
let myNSDate = NSDate(timeIntervalSince1970: timeInterval)

I could have also used timeIntervalSinceReferenceDate instead of timeIntervalSince1970 as long as I was consistent. This is assuming that the time interval is in seconds. Note that Java uses milliseconds.

Update

As of Swift 3, the conversion would use Date rather than NSDate. See this answer for the Swift 3 version.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...