Swift decoding error on date type based on user settings preferences (time format) [duplicate]

1 week ago 14
ARTICLE AD BOX

Recently I have noticed that an API which return a reponse that contains some date type are failing if I have a 12 hour format (AM/PM) on my phone enable iOS 17.6.1. If I switch to 24 hour format the decoding works as expected.

extension DateFormatter { /// Return example: 2022-08-24T17:25:00.000-0400 static let iso8601Full: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" return formatter }() }

I use it on Dependency Container as

let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(.iso8601Full) .. DependencyContainer.register(decoder as JSONDecoder)

The response is like:

optInDateTime = "2025-01-14T12:32:09.179Z";

While the structure is as:

struct Program: Codable, Hashable { let active: Bool let optInDateTime: Date let optOutDateTime: Date? let program: String }

The error message is:

Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "profile", intValue: nil), CodingKeys(stringValue: "loyaltyPrograms", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "optInDateTime", intValue: nil)], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil)) "\n"

A solution that I found can be by adding a local identified "en_US_POSIX". To modify as this

static let iso8601Full: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") print("[Debugg] Locale: \(String(describing: formatter.locale))") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" return formatter }()

Then I have to use the same line wherever I use the DateFormatter class.

I want to know why this happens, what's the difference when I turn on 24 hour format and when 12 hour format, what affect the decoding when then response is the same.

Note: I have been able to produce on iOS 17.1.2 but not on others like 26 and 18, but some users have the issue on versions like 26, its kind of randomly.

Read Entire Article