代码之家  ›  专栏  ›  技术社区  ›  Heath Borders

使用不带GMT时间修饰符的时区的NSDateFormatter将NSDate转换为NSString

  •  20
  • Heath Borders  · 技术社区  · 14 年前

    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 timeZoneWithName:@"GMT"];
    [NSTimeZone timeZoneWithName:@"UTC"];
    [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    
    2 回复  |  直到 13 年前
        1
  •  23
  •   Dickey Singh    12 年前

    如果不想显示时区,请从格式字符串中删除尾部的“z”字符。

    编辑

    另一方面,如果您只想显示时区名称,只需将“z”大写即可。((编辑:对于指定时区,保留“z”小写字母,即PST,对于-0800,保留大写字母“z”)

    小写字母“z”适用于所有其他时区,但不幸的是,GMT是一个特例。所以最简单的方法就是省略'z'并在格式化日期后加上“GMT”。

        2
  •  4
  •   Dickey Singh    12 年前

    接受的答案有一个拼写错误。

    另一方面,如果您只想显示时区名称,只需将“z”大写即可。

    “z”小写表示指定时区,即PST,大写“z”表示-0800

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