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.
To run this Swift code, save it in a file with a .swift
extension and use the Swift command-line tool:
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.