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)



