[英]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
這是一個擴展
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)
搜索完所有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.