简体   繁体   English

Swift:将 ISO8601 转换为 Unix Epoch

[英]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
  • Swift 4 / swift 5斯威夫特 4 / 斯威夫特 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)

After searching all the stackoverflow, I could create a working snippet!!搜索完所有stackoverflow后,我可以创建一个工作片段!!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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