Calculate The Number Of Days Between Two Dates

Fri, Feb 15

I recently had a need to determine the number of days between two dates. Given the abundance of date related support in CocoaTouch, it is a pretty simple process, the biggest challenge is to know which frameworks and methods to call.

One approach to determine the number of days is shown below:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM-dd-yyy"];
 
// To use a specific start date
//  NSDate *startDate = [formatter dateFromString:@"02-16-2013"];
 
// Start with todays date
NSDate *startDate = [NSDate date];
 
// End date
NSDate *endDate = [formatter dateFromString:@"12-28-2013"];
[formatter release];
 
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 
// Notice the components:NSDayCalendarUnit specifier
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                    fromDate:startDate
                                                      toDate:endDate
                                                     options:0];
[gregorianCalendar release];
 
NSLog(@"Days between %@ and %@ is: %d", startDate, endDate, [components day]);

The output will look as follows:

Days between 2013-02-15 02:33:48 +0000 and 2013-12-28 05:00:00 +0000 is: 316

If you have another way to get to the same place, feel free to post a code example.

3 comments

I have often used this technique.

double converter = 60*60*24;

NSDate* date = [NSDate dateWithNaturalLanguageString:@"10/13/2012"];
NSDate* date2 = [NSDate dateWithNaturalLanguageString:@"10/24/2012"];

NSTimeInterval interval = [date2 timeIntervalSinceDate:date];

NSLog(@”%0.f”, interval/converter);

by Sam Mussell on Feb 16, 2013. #

Thanks for the code example Sam.

by John on Feb 17, 2013. #

+ (int)daysBetween:(NSDate *)date1 and:(NSDate *)date2 {
NSUInteger unitFlags = NSDayCalendarUnit;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:unitFlags fromDate:date1 toDate:date2 options:0];
return [components day];

}

by Cesar on Feb 22, 2013. #