Last active
March 3, 2021 08:37
-
-
Save vani2/5fe916b45afcaba7c8c2143ac056adea to your computer and use it in GitHub Desktop.
Date Decoding Strategy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
struct ISODateModel: Codable { | |
let date: Date | |
} | |
var json = """ | |
{ | |
"date": "2018-04-20T14:20:00-0700" | |
} | |
""".data(using: .utf8)! | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .iso8601 | |
let isoModel = try decoder.decode(ISODateModel.self, from: json) | |
print(isoModel.date) //2018-04-20 21:20:00 +0000 | |
struct UnixDateModel: Codable { | |
let date: Date | |
} | |
json = """ | |
{ | |
"date": 1213213123 | |
} | |
""".data(using: .utf8)! | |
decoder.dateDecodingStrategy = .secondsSince1970 | |
let unixModel = try decoder.decode(UnixDateModel.self, from: json) | |
print(unixModel.date) //2008-06-11 19:38:43 +0000 | |
decoder.dateDecodingStrategy = .custom { decoder -> Date in | |
let container = try decoder.singleValueContainer() | |
let unixTime = try container.decode(Double.self) | |
let date = Date(timeIntervalSince1970: unixTime) | |
return date.addingTimeInterval(120) | |
} | |
let customUnixModel = try decoder.decode(UnixDateModel.self, from: json) | |
print(customUnixModel.date) //2008-06-11 19:38:43 +0000 | |
struct FormattedDateModel: Codable { | |
let date: Date | |
} | |
json = """ | |
{ | |
"date": "08-31-2018 18:49" | |
} | |
""".data(using: .utf8)! | |
let dateFormatted = DateFormatter() | |
dateFormatted.dateFormat = "MM-dd-yyyy HH:mm" | |
decoder.dateDecodingStrategy = .formatted(dateFormatted) | |
let formattedModel = try decoder.decode(FormattedDateModel.self, from: json) | |
print(formattedModel.date) //2018-08-31 15:49:00 +0000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment