2011-10-11 71 views
7

我有一個應用程序,顯示某些渡輪旅行的時間表。NSDate獨立於時區?

如果我前往不同的時區 - 比如說4個小時,上午10點的渡輪旅程現在顯示爲6am?

我知道這與日期如何根據他們的時區進行處理有關,但我無法弄清楚如何改變這種行爲。

目前這裏是我如何獲得日期和一個UILabel顯示它:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"HH:mm"]; 
[self.departureTime setText:[dateFormatter stringFromDate:[self.route objectForKey:@"departureTime"]]]; 
[self.arrivalTime setText:[dateFormatter stringFromDate:[self.route objectForKey:@"arrivalTime"]]]; 
[dateFormatter release]; 

在此先感謝您的幫助。

+4

明白的NSDate本身是獨立的時區的 - 它代表UTC(格林威治)時間。您必須設置NSDateFormatter的時區才能生成所需時區的結果。 –

+3

@DanielRHicks日期有* no *時區。它不代表UTC,因爲UTC是時區,日期沒有時區。 –

+0

按照慣例,NSDate中的時間偏移量是相對於UTC的時間偏移量。如果NSDate對象沒有相對於UTC設置,那麼設置NSDateFormatter的時區將是無用的。 –

回答

7

你需要存儲坐輪渡正在發生的時區,並格式化該時區。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"HH:mm"]; 

NSDate *now = [NSDate date]; 
NSLog(@"now:%@", [dateFormatter stringFromDate:now]); 

NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)];  
[dateFormatter setTimeZone:timeZone]; 
NSLog(@"adjusted for timezone: %@", [dateFormatter stringFromDate:now]); 

輸出:

2011-10-10 20:42:23.781 Craplet[2926:707] now:20:42 
2011-10-10 20:42:23.782 Craplet[2926:707] adjusted for timezone: 16:42 
+0

我們可能還需要處理夏令時節約 –

0

不要混淆一個NSDate值與NSLog格式化的輸出。 NSDate的是GMT,蘋果的文檔:

的NSDate,timeIntervalSinceReferenceDate的唯一原始的方法, 提供了在NSDate的界面中的所有其他方法的基礎。 此方法返回一個相對於絕對參考日期的時間值 日期 - 格林威治標準時間2001年1月1日的第一個時刻。

NSTimeInterval referenceInterval = [[dateFormatter dateFromString:@"1 January 2001 GMT"] timeIntervalSinceReferenceDate]; 
NSLog(@"referenceInterval: %f", referenceInterval); 

NSTimeInterval estInterval = [[dateFormatter dateFromString:@"1 January 2001 EST"] timeIntervalSinceReferenceDate]; 
NSLog(@"estInterval:  %f", estInterval); 

輸出:

referenceInterval: 0.000000 
estInterval: 18000.000000 
+0

文檔引用並不意味着「NSDate是格林尼治標準時間「,因爲格林尼治標準時間2001年1月1日可以在任何時區平均表示 –

+0

我只是想了解你的意思是「NSDate是GMT」,因爲我看不出任何方式,NSDate值有任何一個時區的內部概念優先於任何其他(包括GMT)。除了文檔中任意引用格林尼治標準時的引用日期這一事實,並且如果未明確提供時區,NSDate可能會默認在接受字符串時識別爲GMT。 –

+0

當然可以 - 例如相對於2001年1月1日02:00布達佩斯時間爲0.0。 –

1

您還可以使用NSDateComponents類如蘋果的參考描述:

如果你需要創建一個獨立於時區的日期,可以將日期存儲爲NSDateComponents對象 - 只要您存儲對相應日曆的引用即可。

在iOS中,NSDateComponents對象可以包含日曆,時區和日期對象。因此,您可以將日曆與組件一起存儲。如果您使用NSDateComponents類的日期方法來訪問日期,請確保關聯的時區是最新的。

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtTimeZones.html#//apple_ref/doc/uid/20000185-SW1

-1
 NSDate *currentDateTime = datePicker.date; 
     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
     [dateFormatter setDateFormat:@"EEE,MM-dd-yyyy HH:mm:ss"]; 
     NSString *dateInStringFormated = [dateFormatter stringFromDate:currentDateTime]; 
     NSLog(@"%@", dateInStringFormated);