首页 > 解决方案 > 如何将日期字符串从 JSON 解码为 Date 对象?

问题描述

如何将时间戳从 JSON 解码为日期?

我从服务器获取我的日期作为 Json,如下所示:

{

        "date": "2610-02-16T03:16:15.143Z"

    }

我试图从中构建一个 Date 类:

class Message : Decodable {

  var date: Date

}

它没有按预期工作我收到此错误:

Failed to fetch messages: typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "date", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))

标签: jsonswiftxcode

解决方案


像这样解码日期信息时,您需要使用自定义dateDecodingStrategy,并设置日期解析器的时区和语言环境:

let data = """
{
    "date": "2610-02-16T03:16:15.143Z"
}
""".data(using: .utf8)!

struct Message: Codable {
    let date: Date
}

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(identifier: "GMT")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)

do {
  let message = try decoder.decode(Message.self, from: data)
  print(message.date)
} catch {
  print(erroor)
}

推荐阅读