Skip to content

Instantly share code, notes, and snippets.

@niknovak
Created February 20, 2020 14:19
Show Gist options
  • Save niknovak/e8e318cab0e0f03fd400c651cd44e91b to your computer and use it in GitHub Desktop.
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.
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) ❌")
}
}
@niknovak
Copy link
Author

Output

1985-04-12T23:20:50.52Z ❌
1996-12-19T16:39:57-08:00 ✅ decoded as 1996-12-20 00:39:57 +0000
1996-12-20T00:39:57Z ✅ decoded as 1996-12-20 00:39:57 +0000
1990-12-31T23:59:60Z ❌
1990-12-31T15:59:60-08:00 ❌
1937-01-01T12:00:27.87+00:20 ❌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment