Unix Timestamp in Swift

In Swift, Date().timeIntervalSince1970 returns the current Unix time as a Double of seconds, and Date(timeIntervalSince1970: ts) converts a timestamp back to a Date.

Get & convert epoch time in Swift

import Foundation
let t = Date(timeIntervalSince1970: 1700000000) // 2023-11-14T22:13:20.000Z
let now = Int(Date().timeIntervalSince1970)
Gotcha: timeIntervalSince1970 is a Double with sub-second precision — cast to Int only when you intentionally want whole seconds.

Frequently asked questions

How do I get the current Unix timestamp in Swift?
Int(Date().timeIntervalSince1970) for whole seconds.
How do I convert a timestamp to a Date in Swift?
Date(timeIntervalSince1970: ts) then format with ISO8601DateFormatter.

Other languages

Copied