Created
July 26, 2018 08:01
-
-
Save th3m477/442a0d1da6354dd3b84e3b71df5dca6a to your computer and use it in GitHub Desktop.
Swift JSON Date Decoder for unix millis, secs, ISO8701 with and without fractional seconds
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
extension JSONDecoder { | |
enum DateDecodeError: String, Error { | |
case invalidDate | |
} | |
static var bestDateAttemptDecoder: JSONDecoder { | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .custom({ (decoder) -> Date in | |
let container = try decoder.singleValueContainer() | |
if let dateSecs = try? container.decode(Double.self) { | |
return Date(timeIntervalSince1970: dateSecs) | |
} | |
if let dateSecs = try? container.decode(UInt.self) { | |
return Date(timeIntervalSince1970: TimeInterval(dateSecs)) | |
} | |
let dateStr = try container.decode(String.self) | |
let isoFormatter = ISO8601DateFormatter() | |
isoFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] | |
if let date = isoFormatter.date(from: dateStr) { | |
return date | |
} | |
isoFormatter.formatOptions = [.withInternetDateTime ] | |
if let date = isoFormatter.date(from: dateStr) { | |
return date | |
} | |
log.warning("Cannot decode date"); | |
throw DateDecodeError.invalidDate | |
}) | |
return decoder | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment