ios – Is it NSCalendar bug?

0
50


Why are the last two lines of the output the same?

Use NSCalendar to calculate the diff between startTime and endTime, find that the diff between @”2008-02-28 00:00:00″ and @”2022-02-28 00:00:00″ and the diff between @”2008-02-29 00:00:00″ and @”2022-02-28 00:00:00″ are the same. It looks like a bug of NSCalendar, maybe about leapMonth?

code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self printDiffBetweenStartTime:@"2008-02-27 00:00:00" endTime:@"2022-02-28 00:00:00"];
    [self printDiffBetweenStartTime:@"2008-02-28 00:00:00" endTime:@"2022-02-28 00:00:00"];
    [self printDiffBetweenStartTime:@"2008-02-29 00:00:00" endTime:@"2022-02-28 00:00:00"];
}

- (void)printDiffBetweenStartTime:(NSString *)startTime endTime:(NSString *)endTime
{
    static NSDateFormatter *dateFormatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dateFormatter = [[NSDateFormatter alloc] init];
        dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        dateFormatter.calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    });
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *startDate = [dateFormatter dateFromString:startTime];
    NSDate *endDate = [dateFormatter dateFromString:endTime];
    
    NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *components = [calendar components:unitFlags fromDate:startDate toDate:endDate options:0];
    NSLog(@"\"%@\" to \"%@\" : %@ year %@ month %@ day %@ hour %@ minute %@ second", startTime, endTime, @(components.year), @(components.month), @(components.day), @(components.hour), @(components.minute), @(components.second));

}

output:

"2008-02-27 00:00:00" to "2022-02-28 00:00:00" : 14 year 0 month 1 day 0 hour 0 minute 0 second
"2008-02-28 00:00:00" to "2022-02-28 00:00:00" : 14 year 0 month 0 day 0 hour 0 minute 0 second
"2008-02-29 00:00:00" to "2022-02-28 00:00:00" : 14 year 0 month 0 day 0 hour 0 minute 0 second