Check this, I used
"(NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSCalendarOptions)opts"
and added localization
- (NSString *) calculateAgeWith :(NSDate *)dateOfBirth {
// if years == 0, dispaly months and days
// if years > 0, display years and months
NSDate *now = [NSDate date];
unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents* diff = [[NSCalendar currentCalendar] components:unitFlags fromDate:dateOfBirth toDate:now options:0];
NSInteger months = diff.month ;
NSInteger days = diff.day ;
NSInteger years = diff.year ;
if (years == 0 && months == 0) {
if (days == 1) {
return [NSString stringWithFormat:@"%d %@", days, NSLocalizedString(@"day", @"")];
} else {
return [NSString stringWithFormat:@"%d %@", days,NSLocalizedString(@"days", @"")];
}
} else if (years == 0) {
if (months == 1) {
if (days == 0) {
return [NSString stringWithFormat:@"1 %@%@",NSLocalizedString(@"and", @""), NSLocalizedString(@"month", @"")];
} else {
return [NSString stringWithFormat:@"1 %@ %d %@",NSLocalizedString(@"month", @""),days,NSLocalizedString(@"days", @"")];
}
} else {
if (days == 0) {
return [NSString stringWithFormat:@"%d %@", months,NSLocalizedString(@"months", @"")];
}
else {
return [NSString stringWithFormat:@"%d %@ %@%d %@", months,NSLocalizedString(@"months", @""),NSLocalizedString(@"and", @""),days,NSLocalizedString(@"days", @"")];
}
}
} else if ((years != 0) && (months == 0)) {
if (years == 1) {
return [NSString stringWithFormat:@"%d %@", years,NSLocalizedString(@"year", @"")];
} else {
return [NSString stringWithFormat:@"%d %@", years,NSLocalizedString(@"years", @"")];
}
} else {
if ((years == 1) && (months == 1)) {
return [NSString stringWithFormat:@"%@ %@%@",NSLocalizedString(@"one year", @""),NSLocalizedString(@"and", @""),NSLocalizedString(@"one month", @"")];
} else if (years == 1) {
return [NSString stringWithFormat:@"%@ %@%d %@", NSLocalizedString(@"one year", @""),NSLocalizedString(@"and", @""), months,NSLocalizedString(@"months", @"")];
} else if (months == 1) {
return [NSString stringWithFormat:@"%d %@ %@%@", years,NSLocalizedString(@"years", @""),NSLocalizedString(@"and", @""),NSLocalizedString(@"one month", @"")];
} else {
return [NSString stringWithFormat:@"%d %@ %@%d %@", years,NSLocalizedString(@"years", @""),NSLocalizedString(@"and", @""), months,NSLocalizedString(@"months", @"")];
}
}
}