THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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
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.
There are multiple ways to get the Current Timestamp in Swift.
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
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
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
You can choose one of the options. Date class is simple and easy to get Current Timestamp .
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts