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...
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.
- (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: NSCalendar, NSDate, NSDateComponents, NSDayCalendarUnit, NSGregorianCalendar, NSMonthCalendarUnit
2 Comments:
This comment has been removed by the author.
By Leonardo, At March 9, 2011 at 11:15 PM
Just 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.
By Biosopher, At May 23, 2011 at 8:51 PM
Post a Comment
Subscribe to Post Comments [Atom]
<< Home