Last Updated: February 25, 2016
·
1.001K
· diogot

Counting the number of midnights between two dates

Math with dates is always tricky, calculate the number of midnights between two days is not an exception.
Here I have extended the example from the Apple documentation to avoid nil dates.

- (NSInteger)midnightsBetweenFromDate:(NSDate *)startDate
                               toDate:(NSDate *)endDate
{    
    if (startDate == nil || endDate == nil)
        return NSNotFound;

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSInteger startDay = [calendar ordinalityOfUnit:NSDayCalendarUnit
                                             inUnit:NSEraCalendarUnit
                                            forDate:startDate];

    NSInteger endDay = [calendar ordinalityOfUnit:NSDayCalendarUnit
                                           inUnit:NSEraCalendarUnit
                                          forDate:endDate];
    [calendar release];

    if (startDay == NSNotFound)
        return startDay;

    if (endDay == NSNotFound)
        return endDay;

    return endDay - startDay;
}