I have to work with backend that can return multiple flavours of iso8601 date format (and some other flavours as well). As far as I know iso8601 DateDecodingStrategy is very peculiar about format. Doing this custom strategy now:
extension DateFormatter {
convenience init(dateFormat: String) {
self.init()
self.dateFormat = dateFormat
self.locale = .init(identifier: "en_US_POSIX")
self.calendar = .init(identifier: .gregorian)
}
static let yyyy_mm_ddThh_mm_ss = DateFormatter(dateFormat: "yyyy-MM-dd'T'HH:mm:ss")
static let yyyy_mm_ddThh_mm_ssZ = DateFormatter(dateFormat: "yyyy-MM-dd'T'HH:mm:ssZ")
static let yyyy_mm_ddThh_mm_ss_SSSSSSS = DateFormatter(dateFormat: "yyyy-MM-dd'T'HH:mm:ss'.'SSSSSSS")
static let mm_d_yyyy_HH_mm_ss_PM = DateFormatter(dateFormat: "mm/d/yyyy HH:mm:ss a")
}
extension JSONDecoder.DateDecodingStrategy {
static let custom: JSONDecoder.DateDecodingStrategy = .custom { decoder in
let container = try decoder.singleValueContainer()
var string = try container.decode(String.self)
let formatter = DateFormatter()
if let date = DateFormatter.yyyy_mm_ddThh_mm_ssZ.date(from: string) {
return date
}
if let date = DateFormatter.yyyy_mm_ddThh_mm_ss.date(from: string) {
return date
}
if let date = DateFormatter.yyyy_mm_ddThh_mm_ss_SSSSSSS.date(from: string) {
return date
}
if let date = DateFormatter.mm_d_yyyy_HH_mm_ss_PM.date(from: string) {
return date
}
print("TODO another format: \(string)")
// put breakpoint here
return Date()
}
}
Is there a better way?