0

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.

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
förschter
  • 740
  • 1
  • 7
  • 24
  • Probably has something to do with formatting minutes instead of months. – Hot Licks May 29 '13 at 20:33
  • The mistake was, as Hot Licks pointed out in my third line of code. "dd/mm/yyyy" would be days/minutes/years the thing I wanted was days/months/years. – förschter May 29 '13 at 20:45

2 Answers2

1

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

NSTimeInterval diff = [secondDate timeIntervalSinceDate:startDate];

york
  • 149
  • 1
  • 11
1

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.

Psiticosis
  • 118
  • 8