NSDateFormatter是否正确格式化我的时区?

时间:2016-07-08 13:48:47

标签: ios objective-c timezone nsdateformatter

我正在使用此代码为服务器交互创建时区戳。

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;

此代码的响应为:UTC + 08:00等等,它取决于您所在的时区。

但有一次我在UTC + 00:00时区。响应是UTCZ而不是UTC + 00:00。

您能解释为什么只有这个时区有格式化问题吗?

1 个答案:

答案 0 :(得分:3)

此处没有格式化问题 - 或者至少NSDateFormatter没有错误。它的行为完全符合记录。从Unicode TR35-31开始,对于' Z'重复5次:

  

带有小时,分钟和可选秒字段的ISO8601扩展格式。 ISO8601 UTC指示器" Z"当本地时间偏移为0时使用。这相当于" XXXXX"说明符。

如果你真的,真的想避开Z,看起来应该使用xxxxx,记录为:

  

带有小时,分钟和可选秒字段的ISO8601扩展格式。 (与XXXXX相同,减去" Z"。)

请注意,如果您只需要小时和分钟,而不是秒,则应使用ZZZxxx。现代时间不太可能对时区产生任何影响 - 很长一段时间以前,分时间偏移已经逐渐消失。