[英]Swift: Convert ISO8601 to Unix Epoch
我想采用 ISO8601 时间戳,如下所示: YYYY-MM-DDTHH:MM:SSZ
,并使用 Swift 将其转换为 Unix 纪元时间戳。
ISO8601DateFormatter
将字符串转换为Date
, timeIntervalSince1970
获取 UNIX 时间戳。
let timestamp = ISO8601DateFormatter().date(from: "2017-07-14T20:00:00Z")!.timeIntervalSince1970
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.