Finding a Person’s Age with C#

The other day I needed to programmatically determine a person’s age on a particular date given their birthday. Instead of thinking, I first searched the Internet. I was truly amazed at the number of really bad solutions posted. One common mistake was to compute the difference between the target date and the birth date as a TimeSpan object and then . . . well I saw all kinds of crazy after that. The problem is really simple – just compute as you would in real life by subtracting years. Here’s one possible simple solution:
static int AgeOn(DateTime date, DateTime dateOfBirth)
  if (date == null || dateOfBirth == null) // generic error
    return 0; // might want to return -1 here
  if (date.Year <= dateOfBirth.Year)
    return 0; // not born yet, or if born cannot have reached 1
  int age = date.Year – dateOfBirth.Year; // may have to modify
  if (date.Month < dateOfBirth.Month) // haven’t hit birthday yet
  else if (date.Month == dateOfBirth.Month && date.Day < dateOfBirth.Day)
  return age;
The code is self-explanatory. Just subtract years from the two dates and subtract 1 if necessary. A call to this method might look like:
int age = AgeOn(DateTime.Now, new DateTime(1980, 6, 15));
This code prints the age, on the current date, of someone born on June 15, 1980.
This entry was posted in Software Test Automation. Bookmark the permalink.