iosobjective-cnsdatecomponentsformatter

NSDateComponentsFormatter's method stringFromDate:ToDate: is returning a different value every second


I am trying to get the number of days between today's date and a future date. I call the following every second:

NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2025];
[components setMonth:1];
[components setDay:1];

NSDate *currentDate = [NSDate date];
NSDate *futureDate = [[NSCalendar currentCalendar] dateFromComponents:components];

NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorNone;
formatter.allowedUnits = NSCalendarUnitDay;
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleAbbreviated;
NSString *remainingDaysAsString = [formatter stringFromDate:currentDate toDate:futureDate];

I print the variable remainingDaysAsString every second and it is always different by a day.

3,551d
3,551d
3,550d
3,550d
3,551d
3,550d
3,551d

Has anyone experienced something similar? Does this seem like a bug with the class?


Solution

  • That is strange and looks like a bug. The result of NSDateComponentsFormatter are correct (in my test) if you specify all units down to seconds:

    formatter.allowedUnits = NSCalendarUnitDay + NSCalendarUnitHour + NSCalendarUnitMinute  + NSCalendarUnitSecond;
    

    A simpler and reliable method to get the number of days between two dates is

    NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSCalendarUnitDay
                                                          fromDate:currentDate
                                                            toDate:futureDate
                                                           options:0];
    NSInteger days = comp.day;