Doing things the hard way…

But only once

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
- (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;
}