2012-10-27 36 views
0

我想測試兩個NSDate對象是否具有相同的年/月/日但具有不同的一天中的時間。這裏是我的代碼:使用NSDateComponents測試時間不同時的日期相等性

NSDate *date1 = [dataDictionary1 valueForKey:@"date"]; 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
calendar.timeZone = [NSTimeZone systemTimeZone]; 
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date1]; 
NSDate *newDate1 = [calendar dateFromComponents:components]; 

NSDate *date2 = [dataDictionary2 valueForKey:@"date"]; 
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
calendar.timeZone = [NSTimeZone systemTimeZone]; 
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date2]; 
NSDate *newDate2 = [calendar dateFromComponents:components]; 

然而,newDate1正在恢復與2012-05-01 05:00:00 +0000newDate22012-05-01 04:00:00 +0000

時間不是零,因爲我的時區不是GMT,但爲什麼兩個小時不相等?你知道更好的方法來測試不同時期的日期是否相等嗎? (也就是說,比獲得最新組件爲每每一天/月/年爲測試平等更有效?)

回答

0

試試這個:

NSDate *date1 = [dataDictionary1 valueForKey:@"date"]; 
long noTime1 = [date1 timeIntervalSinceReferenceDate]/(60*60*24); 

NSDate *date2 = [dataDictionary2 valueForKey:@"date"]; 
long noTime2 = [date2 timeIntervalSinceReferenceDate]/(60*60*24); 

if (noTime1 == noTime2) { 
    // same date 
} 

當然,這只是工作,如果你只是想比較一下日期部分並且不關心實際的日期,月份或年份值。

+0

謝謝,rmaddy。這真的很乾淨。在這個特殊的例子中,我確實需要一天的信息,但是在同一個項目中還有其他的地方,你的答案會非常有用:) – kiks

相關問題