1

I'm trying to get the difference of days between today [NSDate date] and a day that the user selects from a UIDatePicker, d, which will be returned as an integer.

Here's what I'm using to figure out the difference:

NSDate *startDate = d;
NSDate *endDate =  [NSDate date];
NSLog(@"startDate: %@",startDate);
NSLog(@"endDate: %@",endDate);

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSDateComponents *components = [gregorian components:NSDayCalendarUnit
                                            fromDate:endDate
                                              toDate:startDate
                                             options:0];
NSInteger days = [components day];

NSLog(@"Days: %i",days);

Both startDate and endDate are returned correctly, but the problem I get is the day difference I get is wrong. For example, when I select today's date, the difference is 0, when I select tomorrow, the difference is still 0, and when I select the day after, the difference is only 1, when it should be 2.

Does anyone have any ideas on what I could do to fix this? It's driving me crazy and I don't know what the deal is with it.

mhbdr
  • 753
  • 2
  • 10
  • 26

2 Answers2

1
  • For example, when I select today's date, the difference is 0, when I select tomorrow, the difference is still 0, and when I select the day after, the difference is only 1, when it should be 2.

assume tomorrows selected date is 05:00 pm and todays current date is 08:00 PM. Then if try to get the difference between the dates based on the number of day then it should be zero. Because the difference between the above mention dates is 2 hour less then one complete day. I hope this will solve your problem. Always set the component of both the dates which you are comparing to same. Use NSDateComponent for this purpose.

SimplyKiwi
  • 12,376
  • 22
  • 105
  • 191
vikas
  • 827
  • 1
  • 9
  • 19
0

Usually with this type of issue, it has to do with different date formats which causes this exact problem.

Check this question as reference: find total number of days between two dates in iphone

OR

Objective C - calculating the number of days between two dates

Community
  • 1
  • 1
SimplyKiwi
  • 12,376
  • 22
  • 105
  • 191