Swift:将 ISO8601 转换为 Unix 纪元

Swift: Convert ISO8601 to Unix Epoch

我想采用 ISO8601 时间戳,如下所示:YYYY-MM-DDTHH:MM:SSZ,并使用 Swift.

将其转换为 Unix 纪元时间戳

ISO8601DateFormatter将字符串转换为DatetimeIntervalSince1970获取UNIX时间戳。

let timestamp = ISO8601DateFormatter().date(from: "2017-07-14T20:00:00Z")!.timeIntervalSince1970

在搜索了所有的 Whosebug 之后,我可以创建一个工作片段!!

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
  • Swift 4 / swift 5

这是一个扩展

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
}                                                               
}

用法

let epochTime =  "2021-04-14T10:09:10.773Z".dateToEpoch()
print(epochTime)