Jeffrey Payan
Sep 8, 2018 · 1 min read

If only the .iso8061 dateDecodingStrategy let us pass in the formatOptions… or the ISO8061DateFormatter was a DateFormatter. This does work, however:

let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
struct SomeTest: Codable {
let date: Date
enum CodingKeys: String, CodingKey {
case date
}
init(from: decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let dateString = try container.decode(String.self, forKey: .date)
if let date = formatter.date(from: dateString) {
self.date = date
} else {
throw DecodingError.dataCorruptedError(forKey: .date,
in: container,
debugDescription: "Date string does not match format expected by formatter.")
}
}
}
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade