2012-02-01 79 views
0

我的代碼是像下面正從NSCalendar一個的NSDate和NSDateComponents

NSDateComponents *components = [[NSDateComponents alloc] init]; 
components.year = [aDay.year intValue]; // 2012 
components.month = [aDay.month intValue]; // 2 
components.day = [aDay.day intValue]; // 1 
components.hour = components.minute = components.second = 0; 
NSDate *now = [self.calender dateFromComponents:components]; 

約self.calendar,我嘗試了2種方法都:

self.calendar = [NSCalendar currentCalendar]; 
self.calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 

但畢竟這,當我打印日期「現在」,它始終是這樣的:

(gdb) po now 
2012-01-31 16:00:00 +0000 

日期「現在」應該是2012-02-01 00:00:00

顯然有8小時的差異,我現在在中國,所以我在+800時區我猜?

我該如何解決這個問題?我需要處理時區嗎?

非常感謝!

回答

1

好了,你爲什麼不嘗試的時區設置,以自己的喜好之一:

NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"PST"]; 
[calendar setTimeZone:zone]; 

你可以看到著名的時區的列表,包括:

NSArray *timezones = [NSTimeZone knownTimeZoneNames]; 
NSLog(@"%@", timezones); 
+0

謝謝!所以問題仍然是關於時區?有沒有什麼方法可以直接獲取用戶當前的時區?就像[NSCalendar currentCalendar]? – 2012-02-01 05:28:49

+0

我檢查了默認的timeZone,它是默認的Asia/Hebin,所以...我能做些什麼? – 2012-02-01 06:18:17

0

我已經想通了。

它顯示什麼是正確的,因爲NSDate的節省的絕對時間,這樣的時間段總是+0000,

而且最好是通過這種方式保持它,因爲我需要比較:方法的NSDate等

唯一的區別是,當你要將絕對日期翻譯爲本地日期可讀的字符串的用戶,只是照顧它。

相關問題