Search code examples
javajsonswiftalamofirensdateformatter

Converting Date format in Java to Date format in Swift


I have an endpoint in my Java program that returns a date variable of type Date. I'm calling this endpoint from a Swift program using Alamofire and receiving the response as a JSON object. the date that is getting returned is in the format: "2020-03-04 19:18:06.0" in Java. It gets received in my swift program as: "1583367486000"

I'm sure this is the seconds interval since a certain time period but how do I convert that to a Date format (lets say yyyy-mm-dd hh:mm:ss) in Swift?


Solution

  • Try the following.

    let num = 1583367486000
    let dateNum = Double(num/1000)
    let date = Date(timeIntervalSince1970: dateNum)
    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: .gregorian)
    //formatter.timeZone = NSTimeZone.local // for system clock's local time
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let dateStr = formatter.string(from: date) // 2020-03-05 09:18:06 +0000 => GMT