首页 > 解决方案 > ISO8601DateFormatter 返回 nil 用于从有效字符串转换为日期

问题描述

我有一个 ISO8601 字符串,我想将它转换为 Date 对象,但即使它是一个有效的字符串,我仍然得到一个 nil。这是我的代码:

        let isoFormatter = ISO8601DateFormatter()
        isoFormatter.formatOptions = [
            .withFractionalSeconds,
            .withInternetDateTime,
            .withFractionalSeconds,
            .withColonSeparatorInTime,
            .withDashSeparatorInDate
        ]
        let date = isoFormatter.date(from: self)

我的字符串是2020-04-10T21:13:40.880000,同样的事情发生在2020-04-10T21:13:40(没有毫秒)

标签: iosswift

解决方案


.withInternetDateTimewithFullDatewithFullTimewithDashSeparatorInDatewithColonSeparatorInTime的 组合withColonSeparatorInTimeZone。该选项需要字符串中的时区并与 一起使用"2020-04-10T21:13:40.880000Z",请注意尾随Z.

options withDashSeparatorInDate,withColonSeparatorInTime在您的代码中是多余的(除了 duplicate withFractionalSeconds)。


要省略时区,您必须替换 withInternetDateTimewithFullDateandwithTime

let isoFormatter = ISO8601DateFormatter()
  isoFormatter.formatOptions = [
      .withFractionalSeconds,
      .withFullDate,
      .withTime, // without time zone
      .withColonSeparatorInTime,
      .withDashSeparatorInDate
  ]

推荐阅读