2012-12-24 18 views
2

我已經閱讀了一些關於如何在iOS中的兩個日期之間計算差異的線索,下面是一個似乎也由Apple文檔提供的示例,用它來決定兩個日期是否相同(忽略時間)。但是components:方法總是返回year = 0,month = 0,day = 0,即使這兩個日期不同。我不知道爲什麼...我會很感激你的想法...- [NSCalendar組件:fromDate:toDate:options]總是返回0 diff

+ (BOOL)isSameDate:(NSDate*)d1 as:(NSDate*)d2 { 
if (d1 == d2) return true; 
if (d1 == nil || d2 == nil) return false; 

NSCalendar* currCal = [NSCalendar currentCalendar]; 

// messing with the timezone - can also be removed, no effect whatsoever: 
NSTimeZone* tz = [NSTimeZone timeZoneForSecondsFromGMT:0]; 
[currCal setTimeZone:tz]; 

NSDateComponents* diffDateComps = 
[currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit 
     fromDate:d1 toDate:d2 options:0]; 

return ([diffDateComps year] == 0 && [diffDateComps month] == 0 && [diffDateComps day] == 0); 
} 
+0

試試這個比較使用方法日期講到這裏,http://stackoverflow.com/questions/13301980/why-cant-nsdate使用-BE-相比- - 或。在那裏檢查答案。 – iDev

回答

1

好的我發現這個問題,它不會發生在每個日期,只與連續的問題。事實證明,'isSameDate'沒有作爲組件正確實現:即使時間組件不在組件標誌中,fromDate:toDate也會在dec 23 8:00,dec 24 07:59時返回0!但是它會在Dec 23 8:00,Dec 24 8:01返回1。

要解決我的方法,我需要執行別的東西:

NSDateComponents* c1 = 
    [currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit 
     fromDate:d1]; 

NSDateComponents* c2 = 
    [currCal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit 
     fromDate:d2]; 

return ([c1 day] == [c2 day] && [c1 month] == [c2 month] && [c1 year] == [c2 year]);