使用 NSDateFormatter 和 TimeZone(不带 GMT 时间修饰符)将 NSDate 转换为 NSString
我正在这样初始化我的 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];
dateString
现在是:
Thu, 29 Jul 2010 14:58:42 GMT+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"];
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
is now:
Thu, 29 Jul 2010 14:58:42 GMT+00:00
I want to get rid of the "+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.
EDIT
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"];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不想显示时区,请从格式字符串中删除结尾的“z”字符。
编辑
另一方面,如果您只想显示时区名称,只需将“z”设为大写即可。 ((编辑:保留命名时区的小写“z”,即 PST 和 -0800 的大写“Z”))
编辑
小写“z”适用于所有其他时区,但不幸的是 GMT一个特殊情况。因此,最简单的方法就是省略“z”并将“GMT”附加到格式化日期。
Remove the trailing 'z' character from the format string if you don't want to display the time zone.
EDIT
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))
EDIT
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.
接受的答案有一个错字。
保留小写“z”表示指定时区,即 PST,保留大写“Z”表示 -0800
//January 23, 2013(星期三)12:33:46 PST -0800
Accepted answer had a typo.
leave the 'z' lowercase for named timezone, i.e. PST and uppercase 'Z' for -0800
//January 23, 2013 (Wednesday) 12:33:46 PST -0800