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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…