Calculate Age from Date of Birth in Objective-C

Most of the times, in applications, you want to calculate age as a number not a Date string.

Here is a function to convert date to a meaningful integer.


+(NSInteger)age:(NSDate *)dateOfBirth {

 NSCalendar *calendar = [NSCalendar currentCalendar];
 unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
 NSDateComponents *dateComponentsNow = [calendar components:unitFlags fromDate:[NSDate date]];
 NSDateComponents *dateComponentsBirth = [calendar components:unitFlags fromDate:dateOfBirth];

 if (([dateComponentsNow month] < [dateComponentsBirth month]) || 
        (([dateComponentsNow month] == [dateComponentsBirth month]) && ([dateComponentsNow day] < [dateComponentsBirth day])))
 {
    return [dateComponentsNow year] - [dateComponentsBirth year] - 1;

 }else {
    return [dateComponentsNow year] - [dateComponentsBirth year];
 }
}

This entry was posted in iOS and tagged , . Bookmark the permalink.

One Response to "Calculate Age from Date of Birth in Objective-C"

Leave a reply