0

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?

Nelson Matias
  • 453
  • 1
  • 4
  • 15
  • 4
    That is a Unix timestamp, but in milliseconds. Compare e.g. https://stackoverflow.com/q/30109219/1187415. – For the conversion to a yyyy-mm-dd hh:mm:ss format, look up “DateFormatter.” – Martin R Mar 05 '19 at 18:46
  • Possible duplicate of [NSDate timeIntervalSince1970 not working in Swift?](https://stackoverflow.com/questions/30109219/nsdate-timeintervalsince1970-not-working-in-swift) – Joakim Danielson Mar 05 '19 at 20:21
  • You should store and work with date-times as an unformatted value, such as the Unix timestamp [seconds or milliseconds since the epoch](https://en.wikipedia.org/wiki/Unix_time) as Martin mentions, and convert to a formatted date only when you need to show it to a human. – Stephen P Mar 05 '19 at 20:23

1 Answers1

1

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
El Tomato
  • 6,479
  • 6
  • 46
  • 75
  • Perfect! That's exactly what I was looking for. I thought it was in seconds, which is what was confusing me. Thank you! – Nelson Matias Mar 06 '19 at 21:01