簡體   English   中英

ISO8601DateFormatter 返回 nil 用於從有效字符串轉換為日期

[英]ISO8601DateFormatter returning nil for converting from valid string to date

我有一個 ISO8601 字符串,我想將它轉換為日期 object,但即使它是一個有效字符串,我仍然得到一個 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 (沒有毫秒)

.withInternetDateTimewithFullDatewithFullTimewithDashSeparatorInDatewithColonSeparatorInTimewithColonSeparatorInTimeZone的組合。 該選項需要字符串中的時區並與"2020-04-10T21:13:40.880000Z"使用,請注意尾隨Z

withDashSeparatorInDatewithColonSeparatorInTime選項在您的代碼中是多余的(除了重復的withFractionalSeconds之外)。


要省略時區,您必須將withInternetDateTime替換為withFullDatewithTime

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM