在不带GMT时间修改器的情况下,使用具有TimeZone的NSDateFormatter将NSDate转换为NSString [英] Convert NSDate to NSString with NSDateFormatter with TimeZone without GMT Time Modifier

查看:136
本文介绍了在不带GMT时间修改器的情况下,使用具有TimeZone的NSDateFormatter将NSDate转换为NSString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在初始化NSDateFormatter:

I'm initializing my NSDateFormatter thusly:

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];

dateString现在是:

Thu, 29 Jul 2010 14:58:42 GMT+00:00

我想摆脱"+00:00"

I want to get rid of the "+00:00"

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

I'm guessing from http://unicode.org/reports/tr35/tr35-6.html#Time_Zone_Fallback that I might have a localization issue. I'm working around this right now by removing the "+00:00" manually, but that isn't ideal.

编辑

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

I tried a couple of new ways to create the NSTimeZone, but they both produce the same dateString:

[NSTimeZone timeZoneWithName:@"GMT"];
[NSTimeZone timeZoneWithName:@"UTC"];
[NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[NSTimeZone timeZoneWithAbbreviation:@"UTC"];

推荐答案

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

Remove the trailing 'z' character from the format string if you don't want to display the time zone.

编辑

另一方面,如果只想显示时区名称,则将'z'大写. (((将"z"的小写字母保留为指定的时区,即PST,将大写的"Z"保留为-0800))

On the other hand, if you just want to display the timezone name, just make the 'z' uppercase. ((edit: leave the 'z' lowercase for named timezone, i.e. PST and uppercase 'Z' for -0800))

编辑

小写的"z"在所有其他时区都可以正常工作,但是不幸的是,格林尼治标准时间是一种特殊情况.因此,最简单的方法是省略'z',然后将"GMT"附加到格式化日期之后.

Lowercase 'z' works fine for all the other timezones, but unfortunately GMT is a special case. So the easiest thing to do is to just omit the 'z' and append " GMT" to the formatted date.

这篇关于在不带GMT时间修改器的情况下,使用具有TimeZone的NSDateFormatter将NSDate转换为NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆