小编典典

ISO8601DateFormatter不解析ISO日期字符串

swift

我正在尝试解析

2017-01-23T10:12:31.484Z

使用ISO8601DateFormatter提供的本机类,iOS 10但总是失败。如果字符串不包含毫秒,Date则创建对象不会出现问题。

我已经尝试过很多options组合,但总是失败…

let formatter = ISO8601DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.formatOptions = [.withInternetDateTime, .withDashSeparatorInDate, .withColonSeparatorInTime, .withColonSeparatorInTimeZone, .withFullTime]

任何想法?谢谢!


阅读 510

收藏
2020-07-07

共1个答案

小编典典

macOS 10.13之前的版本/ iOS 11 ISO8601DateFormatter不支持包括毫秒在内的日期字符串。

一种解决方法是使用正则表达式删除毫秒部分。

let isoDateString = "2017-01-23T10:12:31.484Z"
let trimmedIsoString = isoDateString.replacingOccurrences(of: "\\.\\d+", with: "", options: .regularExpression)
let formatter = ISO8601DateFormatter()
let date = formatter.date(from: trimmedIsoString)

在macOS 10.13 + / iOS 11+中,添加了新选项以支持小数秒:

static var withFractionalSeconds: ISO8601DateFormatter.Options { get }

let isoDateString = "2017-01-23T10:12:31.484Z"
let formatter = ISO8601DateFormatter()
formatter.formatOptions =  [.withInternetDateTime, .withFractionalSeconds]
let date = formatter.date(from: isoDateString)
2020-07-07