ios - ISO8601DateFormatter 返回 nil 用于从有效字符串转换为日期
问题描述
我有一个 ISO8601 字符串,我想将它转换为 Date 对象,但即使它是一个有效的字符串,我仍然得到一个 nil。这是我的代码:
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [
.withFractionalSeconds,
.withInternetDateTime,
.withFractionalSeconds,
.withColonSeparatorInTime,
.withDashSeparatorInDate
]
let date = isoFormatter.date(from: self)
我的字符串是2020-04-10T21:13:40.880000
,同样的事情发生在2020-04-10T21:13:40
(没有毫秒)
解决方案
.withInternetDateTime
是withFullDate
、withFullTime
、withDashSeparatorInDate
和withColonSeparatorInTime
的 组合withColonSeparatorInTimeZone
。该选项需要字符串中的时区并与 一起使用"2020-04-10T21:13:40.880000Z"
,请注意尾随Z
.
options withDashSeparatorInDate
,withColonSeparatorInTime
在您的代码中是多余的(除了 duplicate withFractionalSeconds
)。
要省略时区,您必须替换 withInternetDateTime
为withFullDate
andwithTime
let isoFormatter = ISO8601DateFormatter()
isoFormatter.formatOptions = [
.withFractionalSeconds,
.withFullDate,
.withTime, // without time zone
.withColonSeparatorInTime,
.withDashSeparatorInDate
]
推荐阅读
- flutter - Flutter multi_image_picker在android上崩溃
- c - 创建二叉搜索树结构并在 C 中正确初始化它
- python - 如何为在 tkinter 中按下创建的按钮的次数创建一个计数器?
- javascript - 安装节点模块“npm install”时出现问题
- python - Input0 与模型层不兼容:预期形状=(None, 256, 256, 3),发现形状=(256, 256, 3)
- python - python截图通过电子邮件发送
- python - hdbscan 问题(ValueError:numpy.ndarray 大小已更改,可能表示二进制不兼容。预期 C 标头为 88,从 PyObject 获得 80)
- google-apps-script - Google Apps 脚本 - 数据查找副本并粘贴到列的最后一个空单元格中
- javascript - 在 JavaScript 循环中计算具有连续根的序列
- javascript - TypeScript 自动将类型转换为整数