Find Age from given DateOfBirth using C#

Hi all,

Just copy the following method in your class and call it with the parameters of date of birth and current date in DateTime format.

public string FindAge(DateTime dob, DateTime currentDate)
{
int years = currentDate.Year - dob.Year;
int months = 0;
int days = 0;
if(currentDate < dob.AddYears(Years) && Years != 0)
{
--years;
}
dob = dob.AddYears(years);
if (dob.Year == currentDate.Year)
{
months = currentDate.Month - dob.Month;
}
else
{
months = (12 - dob.Month) + currentDate.Month;
}
if(currentDate < dob.AddMonths(months) && months != 0)
{
--months;
}
dob = dob.AddMonths(months);
days = (currentDate - dob).Days;
return years + " years " + months + " months " + days + " days";
}

Copy the above code in your class...and call the method..enjoy... ;)

...S.VinothkumaR.

1 comment:

Jack Wu said...

The code is good but with one error as following:

if(currentDate < dob.AddYears(Years) && Years != 0)

you should change "Years" to "years" or it will cause the compile error.