2012-03-12 122 views
1

我知道這個問題被問了一百萬次,我只是找不到解決方案。問題是:我正在修改NSDate以返回當前月份的第一天的日期或下個月的第一天的日期。它似乎工作得很好,除了1件事:它減少了2或3個小時的時間。NSDate和NSDateComponents返回錯誤的日期

代碼:

NSCalendar *theCalendar = [NSCalendar currentCalendar]; 
int comp = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; 
NSDateComponents *theComp = [theCalendar components:comp fromDate:date]; 
[theComp setTimeZone:[NSTimeZone systemTimeZone]]; 
switch (roundingMode) { 
    case FIRST_OF_MONTH: 
     [theComp setDay:1]; 
     return [theCalendar dateFromComponents:theComp]; 
    case FIRST_OF_NEXT_MONTH: 
     [theComp setMonth:theComp.month+1]; 
     [theComp setDay:1]; 
     return [theCalendar dateFromComponents:theComp]; 
} 

這裏的調試器(GDB)輸出:

(gdb) po theComp 
<NSDateComponents: 0x6e26170> 
    TimeZone: Europe/Kiev (EET) offset 7200 
    Calendar Year: 2012 
    Month: 3 
    Day: 1 
(gdb) po date 
2012-03-12 13:05:22 +0000 
(gdb) po [theCalendar dateFromComponents:theComp] 
2012-02-29 22:00:00 +0000 

任何幫助將不勝感激。

謝謝。

回答

5

日期顯示格林威治標準時間:2012-02-29 00:00:00 +00002012-03-01 22:00:00 +0200。另外不要忘記夏令時的變化,這就解釋了爲什麼有時你會得到3小時的差異。

結果日期是正確的,但調試器以GMT格式顯示它。

+0

嗯......奇怪,但它是真的。我確實希望調試器/ NSLog的規格化輸出。謝謝 – Novarg 2012-03-12 14:23:47