Swift convert unix time to date and time

MwcsMac picture MwcsMac · Nov 10, 2014 · Viewed 115.5k times · Source

My current code:

if  let var timeResult = (jsonResult["dt"] as? Double) {
    timeResult = NSDate().timeIntervalSince1970
    println(timeResult)
    println(NSDate())
}

The results:

println(timeResult) = 1415639000.67457

println(NSDate()) = 2014-11-10 17:03:20 +0000 was just to test to see what NSDate was providing.

I want the first to look like the last. The value for dt = 1415637900.

Also, how can I adjust to time zone? Running on iOS.

Answer

Nate Cook picture Nate Cook · Nov 10, 2014

You can get a date with that value by using the NSDate(withTimeIntervalSince1970:) initializer:

let date = NSDate(timeIntervalSince1970: 1415637900)