CodeGuy CodeGuy - 1 year ago 63
Objective-C Question

Objective C - calculating the number of days between two dates

Possible Duplicate:

How can I compare two dates, return a number of days.

I have two dates (as NSString in the form "yyyy-mm-dd"), for example:

NSString *start = "2010-11-01";
NSString *end = "2010-12-01";

I'd like to implement:

- (int)numberOfDaysBetween:(NSString *)startDate and:(NSString *)endDate {



Answer Source
NSString *start = @"2010-09-01";
NSString *end = @"2010-12-01";

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay

components now holds the difference.

NSLog(@"%ld", [components day]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download