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