简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM