date from decodable swift in swift

Assuming you have a JSON which has a date property, you can represent the date in your Swift code as a Date type. Here is how you can decode JSON data with date property using JSONDecoder:

main.swift
struct MyData: Decodable {
    let name: String
    let date: Date
}

let json = """
{
    "name": "Swift",
    "date": "2021-10-27T23:31:05.000Z"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601 // set date decoding strategy

do {
    let myData = try decoder.decode(MyData.self, from: json)
    print(myData)
} catch {
    print(error)
}
386 chars
22 lines

Note that you need to set the dateDecodingStrategy of your JSONDecoder to .iso8601 to correctly decode the date from the JSON string. This will also work for other date formats, not just ISO 8601.

related categories

gistlibby LogSnag