Edward Anthony Edward Anthony - 2 months ago 10x
iOS Question

How to convert unix millis to NSDate on 32 bit iPhone

I want to convert UNIX millis (returned from server) into NSDate using Swift. This is the returned data:

timestamp: 1469263452058

It works perfectly on iPhone 5S and higher. But it failed on iPhone 5 because it's 32 bit.
I also tried to cast the value into Int64 and it crashed.

Please don't hardcode the 1469263452058. I need to store the timestamp into variable before I can convert it to NSTimeInterval.


You have to divide by 1000 the timestamp

For example:

let result = try! NSJSONSerialization.JSONObjectWithData(jsonFromServer, options: [])

if let timestamp = result["timestamp"] as? Double {
    let timeInterval: NSTimeInterval  = timestamp/1000

    print("time interval is \(timeInterval)")
    //Convert to Date
    let date = NSDate(timeIntervalSince1970: timeInterval)

    //Date formatting
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let dateString = dateFormatter.stringFromDate(date)
    print("formatted date is =  \(dateString)")


time interval is 1469263452.058
formatted date is =  23, July 2016 08:44:AM