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
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);
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.