struct DateWrapper {
let dateISO8601: Date
let dateISO8601withFractionalSeconds: Date
let customDate: Date
}
extension DateWrapper {
enum CodingKeys: String, CodingKey {
case dateISO8601, dateISO8601withFractionalSeconds, customDate
}
}
extension DateWrapper: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
dateISO8601 = try container.decodeDate(from: .dateISO8601, using: .iso8601format)
dateISO8601withFractionalSeconds = try container.decodeDate(from: .dateISO8601withFractionalSeconds, using: .iso8601fractionalFormat)
customDate = try container.decodeDate(from: .customDate, using: .customDate)
}
}
let json: String = """
{
"dateISO8601": "2019-03-14T12:53:26",
"dateISO8601withFractionalSeconds": "2019-03-14T12:54:58.28",
"customDate": "03/12/2019 11:13:00"
}
"""
let jsonDecoder = JSONDecoder()
let jsonData = Data(json.utf8)
do {
let parsedDate = try jsonDecoder.decode(DateWrapper.self, from: jsonData)
print(parsedDate)
} catch {
print(error)
}