Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Convert Datetime to Unix Timestamp in Swift

How to convert Datetime to Unix timestamp in Swift

🎈 🎈 🎈
+1

    import Foundation

    // Create a date from a string
    let dateString = "2020-02-20 12:20:11"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    if let date = dateFormatter.date(from: dateString) {
        // Convert Date to Unix timestamp
        let unixTimestamp = date.timeIntervalSince1970
        print("Unix Timestamp: \(Int(unixTimestamp))")
    } else {
        print("Invalid date string")
    }            
        

Output:
Unix Timestamp: 1582201211
Example only. There may be multiple ways to perform this operation.

Code Explanation

In this Swift snippet the date string '2020-02-20 12:20:11' is parsed into a Date object using DateFormatter. The timeIntervalSince1970 property returns the Unix timestamp in seconds since the epoch. It's cast to Int for clarity (since Unix timestamps are typically whole numbers).
The result is printed as a Unix timestamp.


Other useful Swift date functions

Function Description Example
Date(timeIntervalSince1970:) Creates a Date object from a Unix timestamp (seconds since 1970-01-01). Date(timeIntervalSince1970: 1514764800) returns 2018-01-01 00:00:00
timeIntervalSince1970 Returns the number of seconds since 1970-01-01 for a given Date object. date.timeIntervalSince1970 returns 1531656645 (for July 15, 2018).
DateFormatter.dateFormat Sets the format for the DateFormatter to interpret or display a date. dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" sets the format to year-month-day hour:minute:second.
DateFormatter.string(from:) Formats a Date object into a string using the specified format. dateFormatter.string(from: date) returns 2018-01-01 00:00:00
DateFormatter.date(from:) Parses a string into a Date object based on the specified format. dateFormatter.date(from: "2018-07-15 12:30:45") parses the string to create a Date object.
Date() Creates a Date object for the current date and time. Date() returns the current date and time.
Current Unix Timestamp SECONDS SINCE JAN 01 1970

Current UTC Time
2025-08-20
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder
Ad Banner Placeholder