anyone know how to get the age based on a date(birthdate)
im thinking of something like this
string age = DateTime.Now.GetAccurateAge();
and the output will be some thing like 20Years 5Months 20Days
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;
See the answers at How do I calculate someone’s age in C#? for ideas.
public static class DateTimeExtensions
{
public static string ToAgeString(this DateTime dob)
{
DateTime today = DateTime.Today;
int months = today.Month - dob.Month;
int years = today.Year - dob.Year;
if (today.Day < dob.Day)
{
months--;
}
if (months < 0)
{
years--;
months += 12;
}
int days = (today - dob.AddMonths((years * 12) + months)).Days;
return string.Format("{0} year{1}, {2} month{3} and {4} day{5}",
years, (years == 1) ? "" : "s",
months, (months == 1) ? "" : "s",
days, (days == 1) ? "" : "s");
}
}
Not certain that it would always be correct (haven't thought about if there's some cases with leap years etc that might make it fail...), but this is an easy way to get out the year and month:
DateTime bd = DateTime.Parse("2009-06-17");
TimeSpan ts = DateTime.Now.Subtract(bd);
DateTime age = DateTime.MinValue + ts;
string s = string.Format("{0} Years {1} months {2} days", age.Year -1 , age.Month - 1, age.Day - 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With