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 +0000
和newDate2
與2012-05-01 04:00:00 +0000
。
時間不是零,因爲我的時區不是GMT,但爲什麼兩個小時不相等?你知道更好的方法來測試不同時期的日期是否相等嗎? (也就是說,比獲得最新組件爲每每一天/月/年爲測試平等更有效?)
謝謝,rmaddy。這真的很乾淨。在這個特殊的例子中,我確實需要一天的信息,但是在同一個項目中還有其他的地方,你的答案會非常有用:) – kiks