ISO8601DateFormatter不parsingISOdatestring
我试图parsing这个
2017-01-23T10:12:31.484Z
使用由iOS 10
提供的原生ISO8601DateFormatter
类,但总是失败。 如果string不包含毫秒,则创buildDate
对象时没有问题。
我试过这个和许多options
组合,但总是失败…
let formatter = ISO8601DateFormatter() formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.formatOptions = [.withInternetDateTime, .withDashSeparatorInDate, .withColonSeparatorInTime, .withColonSeparatorInTimeZone, .withFullTime]
任何想法? 谢谢!
ISO8601DateFormatter
不支持包括毫秒的datestring。
解决方法是用正则expression式去除毫秒部分。
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 }