NSDateFormatter single digit hour for format "HH"

I'm generating a date for a JSON file like so:

NSDateFormatter *dateFormatterIso8601 = [NSDateFormatter new];
[dateFormatterIso8601 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZZ"];
[jsonDict setObject:[dateFormatterIso8601 stringFromDate:startDate] forKey:@"start"];

How is it possible that this is producing a JSON file with a date string of 2022-07-12T4:04:23GMT+02:00? There is a leading 0 missing for the hour.

Is this a known bug?

Accepted Reply

This is really a question about foundation, not UIKit. But as far as I know, what is missing in your example is that the locale in your date formatter is still the user's locale, so you are getting whatever time format the user has specified.

You can either set the locale accordingly (I believe there is a specific locale for ISO8601) or there is also a NSISO8601DateFormatter which sounds like exactly what you want. The documentation for that is here: https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

Replies

This is really a question about foundation, not UIKit. But as far as I know, what is missing in your example is that the locale in your date formatter is still the user's locale, so you are getting whatever time format the user has specified.

You can either set the locale accordingly (I believe there is a specific locale for ISO8601) or there is also a NSISO8601DateFormatter which sounds like exactly what you want. The documentation for that is here: https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

Exactly right on both points. Thank you for taking the time to guide me to the solution.