Unix timestamps in Swift

Get the current epoch time and convert between timestamps and dates in Swift. Every snippet below is copy-ready.

// note

Date is a Double of seconds since 2001; epoch needs an offset only for display.

Now.swift · current timestamp
let now = Date().timeIntervalSince1970        // seconds (Double)
let nowMs = Int(Date().timeIntervalSince1970 * 1000)
timestamp → date
let ts: TimeInterval = 1700000000
let date = Date(timeIntervalSince1970: ts)
print(ISO8601DateFormatter().string(from: date))
date → timestamp
let date = ISO8601DateFormatter()
    .date(from: "2023-11-14T22:13:20Z")!
let ts = Int(date.timeIntervalSince1970)
// current epoch

— seconds since 1970-01-01T00:00:00Z.

Watch out for these

  • Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
  • Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
  • Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.

Reference: https://developer.apple.com/documentation/foundation/date

advertisement