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 fromDate:startDate toDate:endDate options:0]; [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.