Created
February 21, 2020 18:46
-
-
Save gotev/65f8bdf1e118f5a90235ca28496569d5 to your computer and use it in GitHub Desktop.
iOS ISO8601 Date JSON Decoder
This file contains hidden or 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
let jsonDecoder: JSONDecoder = { | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .custom { decoder in | |
let container = try decoder.singleValueContainer() | |
let string = try container.decode(String.self) | |
let formatter1 = ISO8601DateFormatter() | |
formatter1.formatOptions = [.withInternetDateTime] | |
let formatter2 = ISO8601DateFormatter() | |
formatter2.formatOptions = [.withInternetDateTime, .withFractionalSeconds] | |
guard let date = formatter1.date(from: string) ?? formatter2.date(from: string) else { | |
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Cannot decode date string \(string)") | |
} | |
return date | |
} | |
return decoder | |
}() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment