1

I'm looking to compare NSDate objects based on the day only (ignoring time). Instead of converting the time to 0:00:00, or using NSDateComponent like most solutions (ex. Comparing two NSDates and ignoring the time component)

Does anyone see an issue with converting the date to an int representing the number of days since 1970 with the timeIntervalSince1970 method?

return (int)([date timeIntervalSince1970]/(SECONDS_PER_DAY));
Community
  • 1
  • 1
ndomin
  • 428
  • 4
  • 11
  • 1
    Calendrical calculations are very error-prone. I suggest watching the "Performing Calendar Calculations" keynote presentation from WWDC 2011 on why it is not recommended you do these calculations on your own. – Léo Natan Dec 05 '13 at 23:27
  • There are ways to do this, but they are subject to timezone and DST-caused glitches. Depends on how precise you want to be. – Hot Licks Dec 05 '13 at 23:31

3 Answers3

5

Yes, absolutely. There are an endless number of pitfalls with date math. Use NSDateComponents; they’re not hard.

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *date1Components = [cal components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date1];
NSDateComponents *date2Components = [cal components:NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date2];
NSComparisonResult comparison = [[cal dateFromComponents:date1Components] compare:[cal dateFromComponents:date2Components];
Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
0

Here's a way to convert an NSDate to an NSTimeInterval that represents midnight of the original date without using NSCalendar. Doing this with two NSDate objects would let you compare the two dates without regard to time.

    NSDate *now = [NSDate date]; // Your original date with time
    NSTimeInterval interval = [now timeIntervalSince1970]; // the full interval
    NSDateFormatter *form = [[NSDateFormatter alloc] init];
    [form setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; // Zulu time
    [form setDateFormat:@"A"]; // milliseconds since midnight
    NSString *secondsStr = [form stringFromDate:now];
    NSTimeInterval seconds = [secondsStr integerValue] / 1000.0; // seconds since midnight
    NSTimeInterval justDate = interval - seconds; // interval for date at midnight (Zulu time)

    // For testing purposes
    NSDate *nowDate = [NSDate dateWithTimeIntervalSince1970:justDate];
    NSLog(@"now = %@, interval = %f", now, interval);
    NSLog(@"seconds = %@", secondsStr);
    NSLog(@"justDate = %f, nowDate = %@", justDate, nowDate);

This may or may not be better than using NSCalendar as shown in Noah's answer.

You must definitely not simply divide by SECONDS_PER_DAY. That will simply be wrong.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
0
NSCalendar.currentCalendar().compareDate(date1, toDate: date2, toUnitGranularity: .Day)

Returns NSComparisonResult

Here is what apple talks about it