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