Oleg Gordiichuk Oleg Gordiichuk - 5 months ago 15
Objective-C Question

Is NSDateFormatter correctly format my time zone?

I am using this code to create timezone stamps for the server interaction.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];

//This NSDateFormatter will return timezone in format "UTC+XX:XX"
[dateFormatter setDateFormat:@"'UTC'ZZZZZ"];

NSString *formattedTimeZone = [dateFormatter stringFromDate:[NSDate date]];

return formattedTimeZone;


Response of this code is : UTC+08:00 and so on it is depending in with time zone you are.

But in one case when i am in UTC+00:00 timezone. The response is UTCZ instead of UTC+00:00.

Could you please explain why only this timezone has a formatting problem ?

Answer

There's no formatting problem here - or at least, no bug in NSDateFormatter. It's behaving exactly as documented. From Unicode TR35-31, for 'Z' repeated 5 times:

The ISO8601 extended format with hours, minutes and optional seconds fields. The ISO8601 UTC indicator "Z" is used when local time offset is 0. This is equivalent to the "XXXXX" specifier.

If you really, really want to avoid the Z, it looks like you should use xxxxx, documented as:

The ISO8601 extended format with hours, minutes and optional seconds fields. (The same as XXXXX, minus "Z".)

Note that if you only ever want hours and minutes, never seconds, you should use ZZZ or xxx instead. It's unlikely to make any difference for time zones in modern times - sub-minute offsets were phased out a long time ago.