Epoch in Swift

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Swift.

import Foundation

// Use Date() to get the current date and time
let now = Date()
print(now)

// Get the number of seconds since the Unix epoch
print(now.timeIntervalSince1970)

// Get the number of milliseconds since the Unix epoch
print(Int(now.timeIntervalSince1970 * 1000))

// Get the number of nanoseconds since the Unix epoch
print(Int(now.timeIntervalSince1970 * 1_000_000_000))

// You can also convert integer seconds or nanoseconds
// since the epoch into the corresponding Date
print(Date(timeIntervalSince1970: now.timeIntervalSince1970))
print(Date(timeIntervalSince1970: TimeInterval(now.timeIntervalSince1970)))

To run this Swift code, save it in a file with a .swift extension and use the Swift command-line tool:

$ swift epoch.swift
2023-05-25 12:34:56 +0000
1684997696.123456
1684997696123
1684997696123456000
2023-05-25 12:34:56 +0000
2023-05-25 12:34:56 +0000

In Swift, we use the Date struct to work with dates and times. The timeIntervalSince1970 property gives us the number of seconds since the Unix epoch. To get milliseconds or nanoseconds, we multiply this value by 1000 or 1_000_000_000 respectively.

Unlike Go, Swift doesn’t have built-in methods for getting milliseconds or nanoseconds directly. However, we can easily calculate these values as shown in the example.

To convert from a Unix timestamp back to a Date, we can use the Date(timeIntervalSince1970:) initializer.

Next, we’ll look at another time-related task: date formatting and parsing.