anyone know how to get the age based on a date(birthdate)
im thinking of something like this
string age = DateTime.Now.GetAccurateAge();
This is what I use. It's a combination of the selected answer and this answer.
For someone born on 2016-2-29, on the 2017-3-1 their age outputs:
Years: 1
Months: 1 (28 days for February)
Days: 0
var today = new DateTime(2020,11,4);
//var today = DateTime.Today;
// Calculate the age.
var years = today.Year - dateOfBirth.Year;
// Go back to the year in which the person was born in case of a leap year
if (dateOfBirth.Date > today.AddYears(-years))
{
years--;
}
var months = today.Month - dateOfBirth.Month;
// Full month hasn't completed
if (today.Day < dateOfBirth.Day)
{
months--;
}
if (months < 0)
{
months += 12;
}
Years = years;
Months = months;
Days = (today - dateOfBirth.AddMonths((years * 12) + months)).Days;