Get Unix Epoch Time in Swift

How do you get the seconds from epoch in Swift?


Solution 1:

You can simply use NSDate's timeIntervalSince1970 function.

let timeInterval = NSDate().timeIntervalSince1970

Solution 2:

For Swift 3.0

Date().timeIntervalSince1970

Solution 3:

You can get that using following

Int(Date().timeIntervalSince1970)

This is for current date, if you want to get for a given date

Int(myDate.timeIntervalSince1970)

If you want to convert back from UNIX time epoch to Swift Date time, you can use following

let date = Date(timeIntervalSince1970: unixtEpochTime)

Solution 4:

1 second = 1,000 milliseconds
1 second = 1,000,000 microseconds

Swift's timeIntervalSince1970 returns seconds with what's documented as "sub-millisecond" precision, which I've observed to mean usually microseconds but sometimes one scale (one digit to the right of the decimal) less or more. When it returns a scale of 5 (5 digits after the decimal), I don't know if Swift is dropping the trailing 0 or it couldn't produce 6 scales of precision. But when it returns a scale of 7, that extra digit can be truncated because it's beyond microsecond precision. Therefore, for consistent and precision-true values:

let secondPrecision = Int(Date().timeIntervalSince1970) // definitely precise
let millisecondPrecision = Int(Date().timeIntervalSince1970 * 1_000) // definitely precise
let microsecondPrecision = Int(Date().timeIntervalSince1970 * 1_000_000) // most likely precise

Note that in the year 2038, 32-bit numbers won't be usable for the Unix timestamp, they'll have to be 64-bit.

All that said, millisecond-precision is the true Unix timestamp and the one that, I think, everyone should use. If you're working with an API or a framework that uses the Unix timestamp, most likely it will be millisecond-precise. Therefore, for a true Unix timestamp:

typealias UnixTimestamp = Int

extension Date {
    /// Date to Unix timestamp.
    var unixTimestamp: UnixTimestamp {
        return UnixTimestamp(self.timeIntervalSince1970 * 1_000) // millisecond precision
    }
}

extension UnixTimestamp {
    /// Unix timestamp to date.
    var date: Date {
        return Date(timeIntervalSince1970: TimeInterval(self / 1_000)) // must take a millisecond-precise Unix timestamp
    }
}

let unixTimestamp = Date().unixTimestamp
let date = unixTimestamp.date

Solution 5:

If you don't want to import Foundation, i.e. for Linux use etc, you can use the following from CoreFoundation:

import CoreFoundation

let timestamp = CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970