Calculate age in objective-c

For an iPhone application I’m developing for a client I need to capture the birthdate of a user, and then show their age on a profile screen. I went looking for a function to help with this simple and tedious task, but couldn’t find any example code that could be lifted to help me, so I rolled my own.  Here is what I made, steal as you see fit.

- (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];
  }
}

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Furl
  • NewsVine
  • Reddit
  • StumbleUpon
  • Technorati
  • Pownce
  • Sphinn
  • Spurl
  • TailRank
  • LinkedIn
  • MySpace
  • Many thanks; it's exactly what I needed!
  • Sean C
    Thanks, this is just what I needed.
blog comments powered by Disqus