Unix timestamps in Swift
Foundation's Date is a point in time. timeIntervalSince1970 reads and writes Unix seconds as a Double.
Get the current Unix timestamp
import Foundation
let seconds = Int(Date().timeIntervalSince1970)
let millis = Int64(Date().timeIntervalSince1970 * 1000)
Convert a Unix timestamp to a date
let date = Date(timeIntervalSince1970: 1700000000)
let fromMs = Date(timeIntervalSince1970: 1700000000123 / 1000)
let iso = ISO8601DateFormatter()
iso.string(from: date) // "2023-11-14T22:13:20Z"
Convert a date to a Unix timestamp
var c = DateComponents()
c.year = 2026; c.month = 11; c.day = 14; c.hour = 10; c.minute = 0; c.second = 0
var cal = Calendar(identifier: .gregorian)
cal.timeZone = TimeZone(identifier: "UTC")!
let epoch = Int(cal.date(from: c)!.timeIntervalSince1970) // 1794650400
Timezones
let f = DateFormatter()
f.locale = Locale(identifier: "en_US_POSIX")
f.timeZone = TimeZone(identifier: "Asia/Kolkata")
f.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZZ"
f.string(from: Date(timeIntervalSince1970: 1700000000)) // "2023-11-15 03:43:20 +05:30"
Common mistakes
timeIntervalSinceReferenceDateandDate(timeIntervalSinceReferenceDate:)count from 2001-01-01, not 1970. Mixing them up shifts dates by 31 years. See Cocoa time.- Set
localetoen_US_POSIXon fixed-format DateFormatters. Otherwise user settings such as a 12-hour clock change the output. timeIntervalSince1970is a Double. Convert to milliseconds before rounding, not after.
Complete example
import Foundation
let now = Int(Date().timeIntervalSince1970)
print("Now:", now)
let d = Date(timeIntervalSince1970: 1700000000)
print("UTC:", ISO8601DateFormatter().string(from: d))
print("Back:", Int(d.timeIntervalSince1970))
Check any value with the epoch converter, or convert a whole column with the batch converter. All examples use 1700000000 (2023-11-14 22:13:20 UTC) and 1794650400 (2026-11-14 10:00:00 UTC).