Skip to content

Instantly share code, notes, and snippets.

@th3m477
Created July 26, 2018 08:01
Show Gist options
  • Save th3m477/442a0d1da6354dd3b84e3b71df5dca6a to your computer and use it in GitHub Desktop.
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
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