- (int)daysBetweenDates:(NSDate *)dt1:(NSDate *)dt2 {
int numDays;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:dt1 toDate:dt2 options:0];
numDays = [components day];
[gregorian release];
return numDays;
}
Line 3: I first get a reference to the calendar. (The date objects don't mean much with a calendar reference.)
Line 4: I set the flags of the date parts that I care about for this task. (Note, in this case I don't use NSMonthCalendarUnit, but show it as an example of how to declare multiple flags.)
Line 5: This does the work of determining how many units (days, months, whatever is chosen on Line 4) separate the two dates.
Line 6: Get the component I'm looking for--days in this case.
Hope you'll find this to be a useful addition to your Cocoa toolbox.
This comment has been removed by the author.
ReplyDeleteJust to point out a mistake I made based on the Subject of this post, you should remove the 'NSMonthCalendarUnit' unitFlag if you really want the total days. As currently written, you get months + days.
ReplyDelete