我想采用ISO8601时间戳,如下所示:YYYY-MM-DDTHH:MM:SSZ
,并使用Swift将其转换为Unix纪元时间戳。
答案 0 :(得分:2)
ISO8601DateFormatter
将字符串转换为Date
,timeIntervalSince1970
获取UNIX时间戳。
let timestamp = ISO8601DateFormatter().date(from: "2017-07-14T20:00:00Z")!.timeIntervalSince1970
答案 1 :(得分:1)
这是一个扩展
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)
答案 2 :(得分:0)
在搜索完所有 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