Search code examples
iosnsdateformatteruidatepickernstimezone

Date selected from UIDatePicker is different from the date being saved


This is how I setup my datePicker

self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.timeZone = [NSTimeZone localTimeZone];

This is how I save the date that I selected

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
dateToSave = [formatter dateFromString:self.dateTextField.text];
NSLog(@"date saved = %@", dateToSave);

If I select Nov 18 2013 from the date picker, the NSLog shows

date saved = 2013-11-17 16:00:00 +0000

However, somewhere in my code, I need to get the difference in days between today's date and the date that I selected in the datepicker.

NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:[NSDate date] toDate:dateSaved options:0];
NSLog(@"number of days => %i", [dateComponents day]);

Today is Nov 10. The date I saved is Nov 18. But the number of days difference is 7, instead of 8.


Solution

  • (This answer refers to the updated question about calculating the number of days between two dates.)

    The problem is that [NSDate date] is the current date+time, not the start of the current day. For example, if

     [NSDate date] = "2013-11-10 10:00:00"
     dateSaved     = "2013-11-18 00:00:00"    (both in your *local* timezone)
    

    then the difference between these two dates is "7 days and 14 hours". Therefore you get 7 as the number of days.

    So you have to calculate the start of the current day first:

    NSDate *startOfDay;
    [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
                                    startDate:&startOfDay
                                     interval:NULL
                                      forDate:[NSDate date]];
    

    and then use it in the calculation of the difference:

    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
                                               fromDate:startOfDay
                                                 toDate:dateSaved
                                                options:0];