How Can I Decode Date String to Date Object from Json?

How Can I Decode Date String to Date Object from Json?

How can I decode timestamp to Date from JSON?

I get my date from the server as Json like this:

{

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

    }

and im trying to build a Date class from it:

class Message : Decodable {

  var date: Date

}

its not working as Expected I am getting this error:

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))

1 Answer

When decoding date info like this, you need to use a custom dateDecodingStrategy, and set the date parser's timezone and locale:

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)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.