使用NSDateComponents在时间不同时测试日期相等性

时间:2012-10-27 02:54:54

标签: objective-c nsdate equality nsdatecomponents

我想测试两个NSDate对象是否具有相同的年/月/日但不同的时间。这是我的代码:

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 +0000newDate2 2012-05-01 04:00:00 +0000

小时不是零,因为我的时区不是GMT,但为什么这两小时不相等?您是否知道更好的方法来测试不同时间的日期是否相等? (也就是说,比每个日期/月/年测试相等性更有效?)

1 个答案:

答案 0 :(得分: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
}

当然,这仅适用于您只想比较日期部分而不关心实际的日,月或年值。