Last active
August 20, 2021 10:07
-
-
Save kuotinyen/dc904dadf1193322fab3f3fbfa5560b7 to your computer and use it in GitHub Desktop.
dateDecodingFormatters.swift
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 { | |
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