Age extracted from birth date always off by inconsistent amount

后端 未结 2 1414
小鲜肉
小鲜肉 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:43

    the problem is in this line

    NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                       components:NSYearCalendarUnit
                                       fromDate:birthDate
                                       toDate:now
                                       options:0];
    

    if you want month & days to be calculated you need to include that in the components like this

    NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                           components:( NSYearCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit) 
                                           fromDate:birthDate
                                           toDate:now
                                           options:0];
    

    also your format is wrong for month string

    [tempFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];
    

    should be corrected as

    [tempFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    

    now you will get correct date.

    explanation. as mentioned on apple documentation these are 1-based. so incase you dont provide a value it will put 1 as default. so earlier your month format was "mm" and it was not correctly setting a month for the birthday hence it was 1986-01-16 so now its 2014-04-01 (in singapore). So you get 28 years which is correct.

提交回复
热议问题