Skip to content

Instantly share code, notes, and snippets.

@gotev
Created February 21, 2020 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gotev/65f8bdf1e118f5a90235ca28496569d5 to your computer and use it in GitHub Desktop.
Save gotev/65f8bdf1e118f5a90235ca28496569d5 to your computer and use it in GitHub Desktop.
iOS ISO8601 Date JSON Decoder
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