NSDateFormatter 是否正确格式化了我的时区?
Is NSDateFormatter correctly format my time zone?
我正在使用此代码为服务器交互创建时区戳。
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。
你能解释一下为什么只有这个时区有格式问题吗?
这里没有格式问题 - 或者至少 NSDateFormatter
中没有错误。它的行为与记录的完全一样。来自 Unicode TR35-31,'Z' 重复 5 次:
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.
如果你真的非常想避免 Z,看起来你应该使用 xxxxx
,记录为:
The ISO8601 extended format with hours, minutes and optional seconds fields. (The same as XXXXX, minus "Z".)
请注意,如果您只需要小时和分钟,而不是秒,则应改用 ZZZ
或 xxx
。在现代,它不太可能对时区产生任何影响 - 亚分钟偏移量在很久以前就被淘汰了。
我正在使用此代码为服务器交互创建时区戳。
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。
你能解释一下为什么只有这个时区有格式问题吗?
这里没有格式问题 - 或者至少 NSDateFormatter
中没有错误。它的行为与记录的完全一样。来自 Unicode TR35-31,'Z' 重复 5 次:
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.
如果你真的非常想避免 Z,看起来你应该使用 xxxxx
,记录为:
The ISO8601 extended format with hours, minutes and optional seconds fields. (The same as XXXXX, minus "Z".)
请注意,如果您只需要小时和分钟,而不是秒,则应改用 ZZZ
或 xxx
。在现代,它不太可能对时区产生任何影响 - 亚分钟偏移量在很久以前就被淘汰了。