Created
February 20, 2020 14:19
-
-
Save niknovak/e8e318cab0e0f03fd400c651cd44e91b to your computer and use it in GitHub Desktop.
Apple docs state that setting dateDecodingStrategy to .iso8601 will decode the ISO-8601-formatted string (in RFC 3339 format) to Date object. But most of the example date formats from https://www.ietf.org/rfc/rfc3339 fail to parse.
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
import UIKit | |
struct Event: Codable { | |
var date: Date | |
} | |
/* | |
Apple docs state that setting dateDecodingStrategy to .iso8601 will decode the ISO-8601-formatted string (in RFC 3339 format) to Date object. | |
But most of the example date formats from https://www.ietf.org/rfc/rfc3339 fail to parse. | |
*/ | |
let dates = ["1985-04-12T23:20:50.52Z", | |
"1996-12-19T16:39:57-08:00", | |
"1996-12-20T00:39:57Z", | |
"1990-12-31T23:59:60Z", | |
"1990-12-31T15:59:60-08:00", | |
"1937-01-01T12:00:27.87+00:20"] | |
for date in dates { | |
let json = "{ \"date\": \"" + date + "\" }" | |
guard let data = json.data(using: .utf8) else { break } | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .iso8601 | |
if let event = try? decoder.decode(Event.self, from: data) { | |
print("\(date) ✅ decoded as \(event.date)") | |
} else { | |
print("\(date) ❌") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output