2012-07-26 61 views
0

我一直使用NSCalendar和NSDateComponents來返回兩個日期之間的差異(天)。這是我用來獲取該代碼的代碼。iOS - TimeZone問題與2個NSDates之間的差異

NSCalendar *calendar = [NSCalendar currentCalendar]; 
calendar.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; 

NSDate *todayDate = [NSDate date]; 
NSDateComponents *comps = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) 
           fromDate:todayDate]; 
[comps setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

NSDate *today = [calendar dateFromComponents:comps]; 

NSDate *startDate = self.date; 
NSDate *endDate = today; 
NSLog(@"startDate: %@",startDate); 
NSLog(@"endDate: %@",endDate); 

NSDateComponents *components = [calendar components:NSDayCalendarUnit 
              fromDate:endDate 
               toDate:startDate 
              options:0]; 
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 

NSInteger days = [components day]; 

怪異的是,這一天期間的早期部分作品完美,但一旦我達到約6或晚上7點(我使用山區標準時間,也就是北京時間我認爲),它停止正常工作。它不是返回正確的差值,而是返回差值減1天。所以例如,它返回-1而不是0或1而不是2.

我猜這是一個時區問題。有誰知道如何修理它?我已經嘗試將我的NSCalendar和NSDateComponents的時區設置爲GMT,本地和系統,但似乎沒有任何工作。

任何想法?

謝謝!

+1

你需要在*之前用'[日曆組件...]'來使用時區*。 – 2012-07-26 01:31:20

回答

0

看起來代碼沒有處理天之間的分數差異。例如,如果開始日期是昨天下午11:59,並且結束日期是今天上午12:01,則​​代碼將報告差異爲0天。如果你認爲這是一天的差異,那麼代碼需要處理這種情況。

如果您使用日期選擇器選擇self.date,則self.date包含日期和當前本地時間。在當地時間下午6點或晚上7點,這是午夜格林尼治標準時間(即明天WRT當地時間),導致差異計算中意外的-1。