Skip to content

Instantly share code, notes, and snippets.

@kuotinyen
Last active August 20, 2021 10:07
Show Gist options
  • Save kuotinyen/dc904dadf1193322fab3f3fbfa5560b7 to your computer and use it in GitHub Desktop.
Save kuotinyen/dc904dadf1193322fab3f3fbfa5560b7 to your computer and use it in GitHub Desktop.
dateDecodingFormatters.swift
extension JSONDecoder {
var dateDecodingFormatters: [DateFormatter]? {
get { return nil }
set {
guard let formatters = newValue else { return }
self.dateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
let dateString = try container.decode(String.self)
for formatter in formatters {
if let date = formatter.date(from: dateString) {
return date
}
}
return Date.invalid
}
}
}
}
extension Date {
// The distancePast display text is "0001/01/01", which is an invalid date replacement since we must return non optional date in dateDecodingStrategy.
static var invalid: Date { .distantPast }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment