使用NSDateFormatter使用NSDateFormatter将NSDATE与无GMT Time修饰符的NSDateFormatter转换为NSString
-
02-10-2019 - |
题
我这样初始化了我的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
我想摆脱“+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"];
解决方案
如果您不想显示时区,请从格式字符串中删除尾随的“ Z”字符。
编辑
另一方面,如果您只想显示时区名称,只需制作“ Z”大写。 ((编辑:将'z'小写用于命名时区,即pst和大写'z'for -0800)))))
编辑
小写“ Z”适合所有其他时区,但不幸的是GMT是一种特殊情况。因此,最简单的事情就是省略“ Z”并将“ GMT”附加到格式的日期。
其他提示
公认的答案有错别字。
另一方面,如果您只想显示时区名称,只需制作“ Z”大写。
将“ Z”小写为命名时区,即PST和大写“ Z”
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMMM dd, yyyy (EEEE) HH:mm:ss z Z"];
NSDate *now = [NSDate date];
NSString *nsstr = [format stringFromDate:now];
// 2013年1月23日(星期三)12:33:46 PST -0800
不隶属于 StackOverflow