Get Current Unix Epoch Time in Swift with examples

This article, Shows how to get the Current Timestamp or Unix Timestamp, or epoch timestamp in Swift. We will use one of the below methods

  • NSDate.timeIntervalSince1970
  • Date().timeIntervalSince1970
  • CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970

Epoch timestamp or Unix timestamp is a long number in milliseconds to refer to a time of a day. It is a Count of milliseconds elapsed since 1970-01-01 UTC.

How to get the Current Unix Epoch timestamp in Swift

There are multiple ways to get the Current Timestamp in Swift.

  • using NSDate class

Foundation library has NSDate class, that contains timeIntervalSince1970 function. It returns a number of seconds since 1979-01-01 UTC.

import Foundation;
let timestamp = NSDate().timeIntervalSince1970

//Returns Seconds
print(Int(timestamp))
// Returns Milli seconds
print(Int(timestamp*1_000))
// Returns Microseconds
print(Int(timestamp*1_000_000))

Output:

1662551864
1662551864065
1662551864065050
  • use Date class The date class in Foundation has a timeIntervalSince1970 method that returns seconds.

Here is an example

import Foundation;

let timestamp1 = Date().timeIntervalSince1970
//Returns Seconds
print(Int(timestamp1))
// Returns Milli seconds
print(Int(timestamp1*1_000))
// Returns Microseconds
print(Int(timestamp1*1_000_000))

Output:

1662551903
1662551903943
1662551903943577
  • use CoreFoundation CFAbsoluteTimeGetCurrent This is another way of getting timestamps in seconds using coreFoundation CFAbsoluteTimeGetCurrent class
import Foundation;
import CoreFoundation

let timestamp2 = CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970
//Returns Seconds
print(Int(timestamp2))
// Returns Milli seconds
print(Int(timestamp2*1_000))
// Returns Microseconds
print(Int(timestamp2*1_000_000))

Output:

1662552042
1662552042111
1662552042111675

Conclusion

You can choose one of the options. Date class is simple and easy to get Current Timestamp .