bCM bCM - 5 months ago 9
iOS Question

Miliseconds to Date

Trying to convert

1465768996460.76245
to
Date
. I use
http://www.ruddwire.com/handy-code/date-to-millisecond-calculators/#.V2mI-JN97UI to check if the value is right.

Above value should print something like "Sun Jun 12 2016 22:03:16 GMT+0000" which it doesn't.

It gets the time off by approx 20 min and yy-mm-dd is way off.

Using the code

print(NSDate(timeIntervalSinceReferenceDate:NSTimeInterval(1465768996460.76245))))


This prints
48449-05-15 22:34:20 +0000

Answer

The method timeIntervalSinceReferenceDate expects a value in seconds and the reference date is actually 1 January 2001.

Your value seems to be the number of miliseconds after the UNIX epoch. You should use the dateWithTimeIntervalSince1970 constructor instead. Don't forget to divide the number by 1000 to make it to seconds.

let seconds: Double = 1465768996460.76245 / 1000
let date = NSDate(timeIntervalSince1970: seconds)

print(date) //2016-06-12 22:03:16 +0000
Comments