Sunday, 17 June 2018

Calculate Age in C#

Many people struggling while calculating the age of a person. it is useful when you want to inform the user about their birthday's based on their saved date of birth in your system. You can simply calculate it by using the following code
//Assume Customer birth date is stored in 'BirthDate'
//which is 9-Dec-1988
DateTime BirthDate = new DateTime(1988, 12, 9);
// Get current date
DateTime CurrentDate = DateTime.Today;
// Calculate the age.
int AgeInYears = CurrentDate.Year - BirthDate.Year;
// To deal with the leap year, -1 from the age
if (BirthDate > CurrentDate.AddYears(-AgeInYears))
     AgeInYears = AgeInYears - 1;
and the output of the above code is
29

No comments:

Post a Comment