Calculating age from date of birth – C#

This is a really small snippet of code that I have used over and over again.

Imagine you are given date of birth of the person and you have to get the age, how would you go about it?

1. Create a private function and pass it date of birth

2. Subtract the number of years from current year

3. In C#, every day of the year has got a value, an extra check is required to see if the current Day is less than the day the person was born in, for example, if today is 15th of March and the person was born 1st of March, you have to subtract an extra year.

Sample code is given below


private static int CalculateAge(DateTime dateOfBirth)
{
int age = 0;
age = DateTime.Now.Year – dateOfBirth.Year;
if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)
age = age – 1;
return age;
}

view raw

CalculateAge.cs

hosted with ❤ by GitHub

7 thoughts on “Calculating age from date of birth – C#

    1. You would probably need to create dob variable which would include time as well. For example, if the person is born on 14th August 1995 at 3:25:45 pm, you can declare

      DateTime myDob = new DateTime(1995,08,14,15,25,45);

      and then use TimeSpan c# class to find out the exact time difference

      TimeSpan interval = DateTime.Now – myDob;

      and then apply some formatting to display age as per your requirements.

  1. Thanks, really helped. I modified the code to consider leap years.
    private static int CalculateAge(DateTime dateOfBirth)
    {
    int age = 0, dayofyr = 0;
    //if leap year and past february 28
    if (DateTime.IsLeapYear(dateOfBirth.Year) && dateOfBirth.DayOfYear >= 60)
    {
    dayofyr = dateOfBirth.DayOfYear – 1;
    }
    else
    {
    dayofyr = dateOfBirth.DayOfYear;
    }
    age = DateTime.Now.Year – dateOfBirth.Year;
    if (DateTime.Now.DayOfYear < dayofyr)
    age = age – 1;

    return age;
    }

      1. That’s precisely why you need to add a leap year check.

        If my birthday is April 2nd of a leap year, then it’s the 93rd day of the year. But if it’s currently April 2nd of a non-leap year then it’s the 92nd day and the math would subtract 1 when it shouldn’t. It also works the other way.

        If my birthday is April 2nd of a non-leap year, then it’s the 92nd day. But if it’s currently April 1st of a leap year then that is also the 92nd day and it would not subtract 1 when it should.

      2. You need to take the leap year check in to consideration if some one is born on Feb 29. Your implementation will output wrong age if some one is born on Feb 29, checking his age on non leap year after Feb 28.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.