Sonic Master Sonic Master - 9 months ago 84
Swift Question

Convert Timestamp to NSDate

I have a

value timestamp 1477933200000.0 from a JSON, and I want to convert into
. 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 and it showed me the correct date. But all three type (
, and
) 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!

Answer Source

Notice that when you use, 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.