Question

I'm trying to get the difference between two dates and it should be displayed in days.

NSLog(@"%@", [NSDate date]);

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/mm/yyyy"];

NSDate *formattedDate = [formatter dateFromString: [NSString stringWithFormat:@"31/05/2013"]];


NSDate *startDateForDays = [NSDate date];
NSDate *endDateForDays = formattedDate;

NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlagsForDays = NSDayCalendarUnit;

NSDateComponents *componentsForDays = [gregorian components:unitFlagsForDays
                                                   fromDate:startDateForDays
                                                     toDate:endDateForDays options:0];

NSLog(@"%@", [NSString stringWithFormat:@"%i days until %@", [componentsForDays day], formattedDate]);

The output looks like this:

2013-05-29 20:21:51 +0000
118 days until 2013-01-30 23:05:00 +0000

I have no idea what in my code is wrong and I hope you could help me.

Was it helpful?

Solution

I realize you have solved your problem, just pointing out you could simplify a bit by leaving out the unsigned integer bit.

NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                fromDate:startDate
                                                  toDate:endDate
                                                 options:0];

This should be a comment not an answer, but I can't comment even though I should be able to.

OTHER TIPS

Try this ------------>

NSTimeInterval diff = [secondDate timeIntervalSinceDate:startDate];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top