Thursday, March 29, 2012

C# age function

Hi readers this is a function developed to get the age on a given date.
feel free to use it.
Inputs are Date of Birth and the date to compare
if you want to get the Age as of Today set the second argument as DateTime.Today.

public static int calculateAge(DateTime DateOfBirth,DateTime DateAsOF)
{
   int years = DateAsOF.Year - DateOfBirth.Year-1;
            
   if (DateAsOF.Month > DateOfBirth.Month)
   {
      years++;
   }
   else if (DateAsOF.Month == DateOfBirth.Month)
   {
      if (DateAsOF.Day>=DateOfBirth.Day)
      {
          years++;
      }

   }
   return years;
}