Alex Rivera | Logout

Number of days between two NSDates

Asked 2011-01-19T19:02:29.083
156

How could I determine the number of days between two NSDate values (taking into consideration time as well)?

The NSDate values are in whatever form [NSDate date] takes.

Specifically, when a user enters the inactive state in my iPhone app, I store the following value:

exitDate = [NSDate date];

And when they open the app back up, I get the current time:

NSDate *now = [NSDate date];

Now I'd like to implement the following:

-(int)numberOfDaysBetweenStartDate:exitDate andEndDate:now
Edit
Report

1 Answer

8

I needed the number of days between two dates including the beginning day. e.g. days between 14-2-2012 and 16-2-2012 would produce a result of 3.

+ (NSInteger)daysBetween:(NSDate *)dt1 and:(NSDate *)dt2 {
        NSUInteger unitFlags = NSDayCalendarUnit;
        NSCalendar* calendar = [NSCalendar currentCalendar];
        NSDateComponents *components = [calendar components:unitFlags fromDate:dt1 toDate:dt2 options:0];
        NSInteger daysBetween = abs([components day]);
    return daysBetween+1;
}

Note that it doesn't matter in which order you provide the dates. It will always return a positive number.

answered 2012-05-16T14:27:31.013

Your Answer