Search code examples
iosiphoneobjective-cnsdatenscalendar

Find out if two calendar days have past between two dates


I want to find out if two calendar days have past between two dates.

I tried using

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date toDate:now options:0];
NSInteger days = [components day];  

and check if days >= 2, but it seems that its count days only if full day has past.

For example if the two dates are:
Monday 01:00 am
Sunday 11:00 pm

the result will be 0,
I expected to get 1 because Sunday is different day than monday.


Solution

  • You have to "normalize" both dates to the start of the respective day:

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDate *startOfToday, *startOfOtherDay;
    [cal rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];
    [cal rangeOfUnit:NSDayCalendarUnit startDate:&startOfOtherDay interval:NULL forDate:date];
    

    and then compute the difference:

    NSDateComponents *components = [cal components:NSDayCalendarUnit fromDate:startOfOtherDay toDate:startOfToday options:0];
    NSInteger days = [components day];