问题描述
我正在尝试解析这个
2017-01-23T10:12:31.484Z
使用 iOS 10
提供的原生 ISO8601DateFormatter
类,但总是失败.如果字符串不包含毫秒,则创建 Date
对象没有问题.
using native ISO8601DateFormatter
class provided by iOS 10
but always fails.If the string not contains milliseconds, the Date
object is created without problems.
我尝试过这个和许多 options
组合但总是失败......
I'm tried this and many options
combination but always fails...
let formatter = ISO8601DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.formatOptions = [.withInternetDateTime, .withDashSeparatorInDate, .withColonSeparatorInTime, .withColonSeparatorInTimeZone, .withFullTime]
有什么想法吗?谢谢!
推荐答案
macOS 10.13/iOS 11 之前的ISO8601DateFormatter
不支持包含毫秒的日期字符串.
Prior to macOS 10.13 / iOS 11 ISO8601DateFormatter
does not support date strings including milliseconds.
解决方法是使用正则表达式删除毫秒部分.
A workaround is to remove the millisecond part with regular 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+ 中添加了一个新选项以支持小数秒:
In macOS 10.13+ / iOS 11+ a new option is added to support fractional seconds:
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)
这篇关于ISO8601DateFormatter 不解析 ISO 日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!