如何在 Swift / Codable 中解码日期?

问题描述

我在 JSON 中有这个日期:2021-07-31T00:00:00+02:00 非常标准。

我的 Postgre sql 将日期存储为秒,例如 646869600

我应该如何设置解码器?

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .deferredToDate
let o7 = try! decoder.decode(Organization.self,from: o6)

我尝试了这三个:.deferredToDate.iso8601.secondsSince1970。都提出了同样的错误

预期解码 Double 但找到了一个字符串/数据。

怎么了?

解决方法

这是标准的 ISO8601 日期格式。日期解码策略.iso8601可以解码。

let jsonString = """
{"date":"2021-07-31T00:00:00+02:00"}
"""

struct Organization : Decodable {
    let date : Date
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let o7 = try! decoder.decode(Organization.self,from: Data(jsonString.utf8))

print(o7.date) // 2021-07-30 22:00:00 +0000

Int 格式似乎是“自参考日期以来的秒数”(1.1.2001)

let seconds = o7.date.timeIntervalSinceReferenceDate
,

问题不在于日期格式。您甚至可以使用自定义 dateFormatter (see here for more information),然后将其分配给解码器:

let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .formatted(customFormatter)

但是!

它会返回一个 Date 并且似乎您在 Double 结构中使用了 TimeInterval (或 Organization )。 尝试将类型更改为 Date,然后如果您需要以秒为单位的时间,则可以获得 timeInterval

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...