Age extracted from birth date always off by inconsistent amount

后端 未结 2 1412
小鲜肉
小鲜肉 2021-01-29 09:17

I\'m using the following code to convert a user-supplied birthdate to its equivalent years from the current date. The output is always off by an inconsistent amount in years and

2条回答
  •  长发绾君心
    2021-01-29 09:17

    Add |NSMonthCalendarUnit|NSDayCalendarUnit to your components, change the date format from yyyy-mm-dd hh:mm:ss to yyyy-MM-dd hh:mm:ss:

    NSDateFormatter *tempFormatter = [[NSDateFormatter alloc] init];
    
    [tempFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate *birthDate = [tempFormatter dateFromString:[NSString stringWithFormat:@"%@-%@-%@ 01:00:00",@"2000", @"04",@"01"]];
    
    NSDate* now = [NSDate date];
    
    NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                       components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                       fromDate:birthDate
                                       toDate:now
                                       options:0];
    NSInteger years = [ageComponents year];
    NSInteger days = [ageComponents day];
    NSInteger months = [ageComponents month];
    NSLog(@"Years: %d, Days: %d, Months: %d",years,days, months);
    

提交回复
热议问题