代码之家  ›  专栏  ›  技术社区  ›  Tirth

如何在我的申请中检索任何国家的当前时间?

  •  1
  • Tirth  · 技术社区  · 14 年前

    我想显示任何国家的当前时间。假设我想知道澳大利亚的美国现在的时间,或者我想看看南非的英国现在的时间,那么我如何检索国家的当前时间?为此,我写了一个代码,但我没有工作,

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterFullStyle];
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    
    NSDate *date = [NSDate date];
    
    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setLocale:usLocale];
    

    上面的代码没有给我正确的时间。

    谢谢

    1 回复  |  直到 14 年前
        1
  •  6
  •   Matthias Bauch    14 年前

    世界上没有美国和澳大利亚的时间。 你必须使用正确的时区,美国大陆有4个,澳大利亚有3个不同的时区。

    要获取墨尔本、柏林和洛杉矶的当前时间(字符串),请使用以下代码:

     NSDate *now = [NSDate date];
     NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
     [df setTimeStyle:NSDateFormatterLongStyle];
     [df setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]];
     NSString *melbourneTime = [df stringFromDate:now];
     [df setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Berlin"]];
     NSString *berlinTime = [df stringFromDate:now];
     [df setTimeZone:[NSTimeZone timeZoneWithName:@"America/Los_Angeles"]];
     NSString *laTime = [df stringFromDate:now];
     NSLog(@"%@", melbourneTime);
     NSLog(@"%@", berlinTime);
     NSLog(@"%@", laTime);
    

    您更改的区域设置对格式有影响。例如,在墨尔本,英语地区的当前时间是 November 18, 2010 9:14:28 PM GMT+11:00 但在德乌德 18. November 2010 21:14:28 GMT+11:00