Cocoa-Matic

iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

Wednesday, September 1, 2010

NSDate number of days between two dates

Date objects in programming are typically both extremely common and notoriously tricky due to the many different syntaxes involved. These rules apply to iPhone development. In one application I created, I needed the number of days between 2 dates in several instances. As there is no simple NSDate2 - NSDate1 function built-in to return the number of days apart, I wrote a function to accomplish the task. Here it is...

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

Labels: , , , , ,

2 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home


« Older Entries  
Newer Entries »