【问题标题】:Swift: Convert ISO8601 to Unix EpochSwift:将 ISO8601 转换为 Unix 纪元
【发布时间】:2017-12-20 00:05:56
【问题描述】:

我想获取 ISO8601 时间戳,例如:YYYY-MM-DDTHH:MM:SSZ,然后使用 Swift 将其转换为 Unix 纪元时间戳。

【问题讨论】:

标签: swift date nsdate epoch iso8601


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    搜索完所有的stackoverflow后,我可以创建一个工作的sn-p!!

    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
    

    【讨论】:

      【解决方案3】:
      • 斯威夫特 4 / 斯威夫特 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)
      

      【讨论】:

      • 不适用于以下字符串 2021-09-20T14:15:22Z 始终返回 0
      猜你喜欢
      • 2017-08-13
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-09
      • 2012-11-07
      • 2011-03-28
      • 2015-07-08
      相关资源
      最近更新 更多