Unix timestamps in Swift

Everything Swift needs for Unix timestamps: the current epoch time in seconds and milliseconds, timestamp-to-date and date-to-timestamp conversion, and ISO 8601 parsing. Swift's Date speaks Unix time through timeIntervalSince1970, but Apple's own frameworks count from 2001, so know which reference you're holding before doing arithmetic. There's a live converter at the bottom for checking any value the snippets produce.

Get the current Unix timestamp

let seconds = Int(Date().timeIntervalSince1970)        // 1700000000
let millis = Int(Date().timeIntervalSince1970 * 1000)  // 1700000000000

Convert a timestamp to a Date

let date = Date(timeIntervalSince1970: 1_700_000_000)

Format for display

let formatter = ISO8601DateFormatter()
formatter.string(from: date)  // "2023-11-14T22:13:20Z"

date.formatted(.dateTime.year().month().day().hour().minute())

Parse an ISO 8601 string

let parsed = ISO8601DateFormatter()
    .date(from: "2023-11-14T22:13:20Z")

For fractional seconds, set formatOptions = [.withInternetDateTime, .withFractionalSeconds]; the default rejects them.

Check a value

Detected: Unix timestamp (seconds)/t/1700000000

Your timezone

UTC · GMT+00:00 · UTC

Tue, Nov 14, 2023, 10:13:20 PM

Common formats

UTC

Tue, Nov 14, 2023, 10:13:20 PM

ISO 8601

2023-11-14T22:13:20.000Z

Unix (seconds)

1700000000

Unix (millis)

1700000000000

Relative

…

Common questions

What is timeIntervalSinceReferenceDate?
Seconds since 2001-01-01, Apple's Cocoa reference date, used by NSDate internals, Core Data, and many Apple databases. It differs from Unix time by exactly 978307200 seconds; decode raw values with the Cocoa timestamp converter on this site.
Why does DateFormatter give nil or wrong dates for API input?
DateFormatter is locale-sensitive: a user's 12/24-hour setting can break fixed-format parsing. For machine formats use ISO8601DateFormatter, or set the formatter's locale to en_US_POSIX.
Does Date carry a timezone?
No. Date is an absolute instant. Zones enter only at formatting/parsing time via the formatter's timeZone property, which defaults to the device's zone.

Related pages