2010-11-18 40 views
1

我想顯示任何國家的當前時間。假設我想查看美國在澳大利亞的當前時間,或者我想查看當前英格蘭在南非的時間,那麼我如何檢索當前的國家時間?爲此,我寫了一個代碼,但我沒有工作,如何檢索我的應用程序中任何國家的當前時間?

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

上述代碼沒有給我正確的時間。

謝謝

回答

6

沒有美國或澳大利亞的時間這樣的事情。 你必須使用正確的時區,美國大陸有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); 

你已經改變了語言環境對格式的影響。例如,en_US語言環境中墨爾本的當前時間爲November 18, 2010 9:14:28 PM GMT+11:00,但在de_DE中爲18. November 2010 21:14:28 GMT+11:00

+0

無論每個國家/地區有多少個時區,我只想在目前的時間在任何國家使用GMT格式? – Tirth 2010-11-18 10:19:40

+0

確實很重要,在澳大利亞有三種不同的「當前時間」。有人必須做出選擇哪一個使用。 – 2010-11-18 10:22:21

相關問題