BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Algorithms and Data Structures
.NET 1.1+

Calculating a Person's Age in Years

Sometimes you will want to calculate the age of a person or of an object and return a result specifying the age in years. This calculation is simple to perform using the properties of the .NET framework's DateTime structure and basic arithmetic operators.

Calculating Ages

It can be useful to calculate the age of a person or object in years. This may be for simple reasons, such as displaying an age in a software application or web site. It may be that products that a company sells are age-restricted and that it is a legal requirement to know the age of the customer. Calculating an age is very simple using the properties of the DateTime structure and basic arithmetic operators.

To calculate an age, we must first determine the difference in years between the person's birth date and the current date. We can then compare the month and day parts of the two dates to determine whether the number of years should be adjusted by one.

29 February

Some people were born on 29 February during a leap year. This must be considered when calculating an age during a non-leap year. English law states that a person born on 29 February becomes aged eighteen on 28 February. Many algorithms for determining a person's age do not consider this special case and incorrectly calculate their age as seventeen until 1 March. The method described in this article caters for this possibility.

Creating the Method

We will create a single method that accepts a parameter containing the date of birth of the person and returns an integer containing the age in years. The method performs three key actions:

  • The current date is assigned to a variable. As there will be more than one operation involving the current date, we will hold the date to avoid the very rare occasion where it may change during the method's execution.
  • The difference between the year parts of the current date and the birth date will be obtained. This will either be the correct age or one year higher than the correct age.
  • The number of years calculated in the previous step will be added to the birth date. If the resultant date is after the current date, we know that the number of years is too high. In this case we will subtract one to determine the age.

The method is as follows:

private static int CalculateAge(DateTime birthDate)
{
    DateTime today = DateTime.Today;

    int age = today.Year - birthDate.Year;
    if (birthDate.AddYears(age) > today)
    {
        age--;
    }
    return age;
}

Executing the Method

We can test the method with a few lines of code as follows. Try changing the birth date to test edge cases.

DateTime birthDate = new DateTime(1972, 12, 3);
int age = CalculateAge(birthDate);
Console.WriteLine("{0} year(s)", age);  // Outputs "36"
18 April 2009