NSDate 到 NSString 的转换不遵循 NSDateFormatter

NSDate conversion to NSString doesn't follow NSDateFormatter

我在将 NSDate 转换为 NSString 时遇到问题,我在方法中有以下代码

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[formatter setTimeZone:timeZone];
[formatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'zzz'"];
return [formatter stringFromDate:date];

如果我没记错的话,这应该是 return 一个像

这样的字符串
"2016-01-15T22:45:40.GMT"

但是生成的字符串取决于设备配置,这意味着如果设备将日期显示为 24 小时,那么我会得到上面的结果,另一方面,如果设备配置为将房子显示为 A.M. P.M。然后我得到

"2016-01-15T10:46:50 p.m..GMT"

From the documentation:

Although in principle a format string specifies a fixed format, by default NSDateFormatter still takes the user’s preferences (including the locale setting) into account. You must consider the following points when using format strings:

In iOS, the user can override the default AM/PM versus 24-hour time setting. This may cause NSDateFormatter to rewrite the format string you set.

我认为,如果您希望结果具有固定的格式,无论用户设置如何,您都必须考虑使用自己的格式化方法。

实际上,from this answer (as pointed out by pbasdf),看来您可以通过简单地设置语言环境来规避此问题:

NSLocale* en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:en_US_POSIX];