Sonic Master
Sonic Master

Reputation: 1246

Convert Timestamp to NSDate

I have a double value timestamp 1477933200000.0 from a JSON, and I want to convert into NSDate then string. This what I did,

let dateNow = NSDate(timeIntervalSinceNow: timestampDouble)
let date1970 = NSDate(timeIntervalSince1970: timestampDouble)
let dateRef = NSDate(timeIntervalSinceReferenceDate: timestampDouble)

let dateFormatter = NSDateFormatter()
// dateFormatter.dateFormat = "MM/dd/YYYY HH:MM:ss a"
dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle

let convDateNow = dateFormatter.stringFromDate(dateNow)
print("Date Now: \(convDateNow)")

let convDate1970 = dateFormatter.stringFromDate(date1970)
print("Date Now: \(convDate1970)")

let convRefDate = dateFormatter.stringFromDate(dateRef)
print("Date Now: \(convRefDate)")

I tried to convert it in http://www.epochconverter.com and it showed me the correct date. But all three type (timeIntervalSinceNow, timeIntervalSince1970, and timeIntervalSinceReferenceDate) is weird. This is the result from those type respectively.

Date Now: September 2, 48850 at 5:50:04 PM
Date Now: November 3, 48803 at 3:00:00 PM
Date Now: November 3, 48834 at 3:00:00 PM

So what I am doing wrong here? I just want to get the difference between date now and the date from json (timestamp).

Any help would be really appreciated. Thank you!

Upvotes: 0

Views: 952

Answers (1)

drhr
drhr

Reputation: 2281

Notice that when you use epochconverter.com, there is a message saying "Assuming that this timestamp is in milliseconds".

Now, try removing the three trailing zeroes (to the left of the decimal). It will now assume you're dealing with seconds and it will give you the same date & time.

In iOS, NSTimeInterval (or TimeInterval in Swift) is indeed typedef'd as a double (or Double), but it is interpreted as seconds (with sub-millisecond precision). Therefore, the various NSDate() constructor overloads are expecting the parameter to be expressed in seconds.

So you may need to divide that timestamp by 1000 to convert from milliseconds to seconds.

Upvotes: 1

Related Questions