jsonswiftdatejsondecoderdateformatter

Date string does not match format expected by formatter


Was only able to reproduce this issue on a friend's device. The device is from Germany and is set to the German region in Settings. I cannot reproduce on any Canadian devices. Why is it failing when trying to create a Date property from the JSON?

Console:

dataCorrupted(Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "60", intValue: nil), CodingKeys(stringValue: "expiration", intValue: nil)], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil))

Struct:

struct TokenResponse: Decodable {
    var ticket : String
    var expiration : Date?
    var sessionId: String
}

Inside URLSession:

do {
    let decoder = JSONDecoder()
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    decoder.dateDecodingStrategy = .formatted(formatter)
    let json = try decoder.decode([String: TokenResponse].self, from: data)
}
catch {
    print(error)
}

JSON:

{
   "60":{
      "ticket":"aVeryLongJWT",
      "expiration":"2022-02-04T22:00:34.8325102Z",
      "sessionId":"aUUID"
   }
}

Solution

  • You should set the locale before setting dateFormat string:

    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    

    See “Working With Fixed Format Date Representations” in DateFormatter documentation.