我正在尝试解析这个问题
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]
任何的想法?谢谢!
在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)