convert a unix timestamp to a date in swift

To convert a Unix timestamp to a date in Swift, you can use the Date(timeIntervalSince1970: TimeInterval) initializer on the Date struct.

Here's an example implementation:

main.swift
func convertUnixTimeToDateString(unixTime: Double) -> String {
    let date = Date(timeIntervalSince1970: unixTime)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Specify date format
    let dateString = dateFormatter.string(from: date)
    return dateString
}
310 chars
8 lines

This function takes in a Unix timestamp (in seconds), creates a new Date object using the timeIntervalSince1970 initializer, and then formats the date into the desired format using a DateFormatter object.

To use this function, you can simply call it and pass in your Unix timestamp as a Double value:

main.swift
let unixTime = 1588583460.0
print(convertUnixTimeToDateString(unixTime: unixTime))
83 chars
3 lines

This would output 2020-05-04 12:44:20, which is the formatted date string for the Unix timestamp 1588583460.

gistlibby LogSnag