本文介绍了ISO8601DateFormatter不解析ISO日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析此

使用 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.

我是尝试了这个和许多选项组合,但总是失败...

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]

有什么想法吗?
谢谢!

Any idea?Thanks!

推荐答案

ISO8601DateFormatter 不支持日期字符串包括毫秒。

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:

这篇关于ISO8601DateFormatter不解析ISO日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 05:09