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;
}
Written by Diogo Tridapalli
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Objective-c
Authors
Related Tags
#objective-c
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#