使用带有TimeZone的NSDateFormatter将NSDate转换为NSString,而不使用GMT时间修改器

Hea*_*ers 20 timezone objective-c nsdateformatter nstimezone

我正在初始化我的NSDateFormatter:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss z"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:date];
Run Code Online (Sandbox Code Playgroud)

dateString 就是现在:

Thu, 29 Jul 2010 14:58:42 GMT+00:00
Run Code Online (Sandbox Code Playgroud)

我想摆脱"+00:00"

我猜测来自http://unicode.org/reports/tr35/tr35-6.html#Time_Zone_Fallback我可能有本地化问题.我现在通过手动删除"+00:00"来解决这个问题,但这并不理想.

编辑

我尝试了几种新方法来创建NSTimeZone,但它们都生成相同的dateString:

[NSTimeZone timeZoneWithName:@"GMT"];
[NSTimeZone timeZoneWithName:@"UTC"];
[NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[NSTimeZone timeZoneWithAbbreviation:@"UTC"];
Run Code Online (Sandbox Code Playgroud)

jle*_*ehr 23

如果您不想显示时区,请从格式字符串中删除尾随的"z"字符.

编辑

另一方面,如果您只想显示时区名称,只需将'z'设为大写.((编辑:保留命名时区的'z'小写,即-0800的PST和大写'Z'))

编辑

小写'z'适用于所有其他时区,但遗憾的是GMT是一个特殊情况.因此,最简单的方法是省略'z'并将"GMT"附加到格式化日期.