0

I want to test if two NSDate objects have the same year/month/day but different times of day. Here is my code:

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];

However, newDate1 is returning with 2012-05-01 05:00:00 +0000 and newDate2 with 2012-05-01 04:00:00 +0000.

The hours are not zero because my time zone is not GMT, but why are the two hours not equal? Do you know a better way to test if dates with differing times are equal? (That is, more efficient than getting date components for each and testing equality for each day/month/year?)

kiks
  • 105
  • 1
  • 7

1 Answers1

0

Try this:

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
}

Of course this only works if you simply want to compare the date portion and don't care about the actual day, month, or year values.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks, rmaddy. That's really clean. In this particular instance, I do need the day info, but there are other spots in this same project where your answer is going to be very useful :) – kiks Oct 27 '12 at 03:14