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;
}
Advertisements

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

    • 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;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s