Convert Date to Integer in Swift

If you are looking for timestamp with 10 Digit seconds since 1970 for API call then, below is code:

Just 1 line code for Swift 4/ Swift 5

let timeStamp = UInt64(Date().timeIntervalSince1970)

print(timeStamp) <-- prints current time stamp

1587473264

let timeStamp = UInt64((Date().timeIntervalSince1970) * 1000) // will give 13 digit timestamp in milli seconds

Date to Int

// using current date and time as an example
let someDate = Date()

// convert Date to TimeInterval (typealias for Double)
let timeInterval = someDate.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 Date

Including the reverse for completeness.

// convert Int to TimeInterval (typealias for Double)
let timeInterval = TimeInterval(myInt)

// create NSDate from Double (NSTimeInterval)
let myNSDate = Date(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.

Note

  • For the old Swift 2 syntax with NSDate, see this answer.