-1

I'd like to take a ISO8601 timestamp, like this: YYYY-MM-DDTHH:MM:SSZ, and convert it to a Unix epoch time stamp using Swift.

dannymout
  • 91
  • 9

3 Answers3

4

ISO8601DateFormatter converts the string to Date, timeIntervalSince1970 gets the UNIX timestamp.

let timestamp = ISO8601DateFormatter().date(from: "2017-07-14T20:00:00Z")!.timeIntervalSince1970
vadian
  • 274,689
  • 30
  • 353
  • 361
0

After searching all the stackoverflow, I could create a working snippet!!

let isoFormatter = ISO8601DateFormatter()
    isoFormatter.formatOptions = [.withFullDate,.withTime, .withFractionalSeconds,.withDashSeparatorInDate,.withColonSeparatorInTime]
    let date = UInt64((isoFormatter.date(from: "2021-04-14T10:09:10.773Z")?.timeIntervalSince1970 ?? 0) * 1000) // your time here with milliseconds
print(date) // prints 1619706315298
vilas deshmukh
  • 389
  • 2
  • 5
0
  • Swift 4 / swift 5

here is an extension

extension String{
func dateToEpoch() -> UInt64 {
    let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [.withFullDate,.withTime, .withFractionalSeconds,.withDashSeparatorInDate,.withColonSeparatorInTime]
let date = UInt64((isoFormatter.date(from: self)?.timeIntervalSince1970 ?? 0) * 1000)
    return date
}                                                               
}

usage

let epochTime =  "2021-04-14T10:09:10.773Z".dateToEpoch()
print(epochTime)
vilas deshmukh
  • 389
  • 2
  • 5
  • Does not work for me with the following string `2021-09-20T14:15:22Z` Returns always `0`. – kuzdu Sep 16 '21 at 12:23