我如何将JSON中的日期字符串解码为Date对象?

问题描述 投票:0回答:1

我如何从JSON中解码时间戳到Date?

我从服务器上得到了我的日期,就像这样的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))
json swift xcode
1个回答
0
投票

当解码这样的日期信息时,你需要使用一个自定义的 "日期 "类。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)
}
© www.soinside.com 2019 - 2024. All rights reserved.