0

The way I am calculating the difference between of 2 dates is

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

NSDateComponents *nowAndEnd     =   [calendar components:NSMonthCalendarUnit|
                                                        NSDayCalendarUnit|
                                                        NSMinuteCalendarUnit
                                                fromDate:now
                                                  toDate:end
                                                 options:0];


NSLog(@"nowAndEnd's day is %d",nowAndEnd.day);
NSLog(@"nowAndEnd's month is %d",nowAndEnd.month);

And I am getting back is

 nowAndEnd's day is 15
 nowAndEnd's month is 1

Question is how can I compute the days from those info. I am asking because some of months have 30 days and some of them have 31...

tranvutuan
  • 6,089
  • 8
  • 47
  • 83

1 Answers1

3

What you did is correct, but if you want the calculation to be performed on days only, just use the NSDayCalendarUnit alone:

NSDateComponents *nowAndEnd    =   [calendar components:NSDayCalendarUnit
                                                fromDate:now
                                                  toDate:end
                                                 options:0];

The answer will be directly calculated to the number of days.

viggio24
  • 12,316
  • 5
  • 41
  • 34
  • thanks for pointing it out. However, the day I am getting is shorter than the actually total days, example is the actually total days is 47, i am getting 46... – tranvutuan Mar 14 '13 at 20:41
  • This is strange. Consider in any case that in the calculation the starting day is not included. So from Jan. 1 to Feb. 5 you have (31-1)+5=35 days and not 36. – viggio24 Mar 14 '13 at 20:49