Calculate The Number Of Days Between Two Dates

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
[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.

  1. 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);

  2. + (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];


Comments are closed.