So, I have iso8601 dates in my json that look like "2016-06-07T17: 20: 00.000 + 02: 00"
Is there a way to parse these iso8601 dates using swift4? Am I missing something?
I tried the following, but only the dateString "2016-06-07T17: 20: 00Z" from jsonShipA is legible ....
import Foundation
struct Spaceship : Codable {
var name: String
var createdAt: Date
}
let jsonShipA = """
{
"name": "Skyhopper",
"createdAt": "2016-06-07T17:20:00Z"
}
"""
let jsonShipB = """
{
"name": "Skyhopper",
"createdAt": "2016-06-07T17:20:00.000+02:00"
}
"""
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let dataA = jsonShipA.data(using: .utf8)!
if let decodedShip = try? decoder.decode(Spaceship.self, from: dataA) {
print("jsonShipA date = \(decodedShip.createdAt)")
} else {
print("Failed to decode iso8601 date format from jsonShipA")
}
let dataB = jsonShipB.data(using: .utf8)!
if let decodedShip = try? decoder.decode(Spaceship.self, from: dataB) {
print("jsonShipA date = \(decodedShip.createdAt)")
} else {
print("Failed to decode iso8601 date format from jsonShipB")
}
Playground Output:
jsonShipA date = 2016-06-07 17:20:00 +0000
Failed to decode iso8601 date format from jsonShipB
Error message: "The expected date string should be formatted in ISO8601 format." But as far as I know, the date "2016-06-07T17: 20: 00.000 + 02: 00" is a valid ISO8601 date
source
share