Reputation: 17778
How do you get the seconds from epoch in Swift?
Upvotes: 152
Views: 101020
Reputation: 2593
You can simply use Date's timeIntervalSince1970
function.
let timeInterval = Date().timeIntervalSince1970
You often want an Int:
let secondsStamp = Int(Date().timeIntervalSince1970)
The result is in seconds. (Not milliseconds, picoseconds, etc.)
"Unix time" aka "unix time stamp" is explained in detail here.
Note that an iOS TimeInterval
is indeed in seconds.
Upvotes: 210
Reputation: 12385
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 assume Swift couldn't produce 6 scales of precision, and when it returns a scale of 7, that extra digit can be truncated because it's beyond microsecond precision. Therefore:
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
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 in Swift:
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
Note that in the year 2038, 32-bit numbers won't be usable for the Unix timestamp, they'll have to be 64-bit, but Swift will handle that for us automatically so we can safely use Int
(and need not use Int64
explicitly).
Upvotes: 12
Reputation: 4176
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
Upvotes: 4
Reputation: 5241
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)
Upvotes: 15