Created
February 15, 2013 14:42
-
-
Save jwv/4960777 to your computer and use it in GitHub Desktop.
Objective-c: Calculate The Number Of Days Between Two Dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment