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