CoderChick
CoderChick

Reputation: 232

Convert Unix timestamp to date object swift 5

I need to convert a unix timestamp into a date object in the swift 5 programming language.

Unix time stamp (represented as an integer)

1616187198

print(unixTimeStamp)  //Output: 1616187198
print(Date())         //Output: 2021-03-19 23:30:30 +0000

How can I convert the integer unix time stamp to be represented the exact same as the Date() object.

My only guess is to use DateFormatter but im not sure how to go about this with a unix timestamp

static let dateFormatter: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = .current
        dateFormatter.timeZone = .current
        dateFormatter.dateStyle = .medium
        dateFormatter.timeStyle = .short
        return dateFormatter
    }()

Upvotes: 0

Views: 532

Answers (1)

matt
matt

Reputation: 535231

Cast the unix time stamp to a Double and call Date(timeIntervalSince1970:).

(Note: That converts the time stamp to a date. But how it is represented visibly, in the console or any other form of string output, is a completely different matter.)

Upvotes: 4

Related Questions