Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# calculate accurate age

Tags:

c#

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

like image 942
reggieboyYEAH Avatar asked Jun 16 '10 15:06

reggieboyYEAH


4 Answers

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;
like image 140
whiscode Avatar answered Sep 22 '22 05:09

whiscode


See the answers at How do I calculate someone’s age in C#? for ideas.

like image 44
Jonathan S. Avatar answered Oct 18 '22 22:10

Jonathan S.


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");
    }
}
like image 59
LukeH Avatar answered Oct 19 '22 00:10

LukeH


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);
like image 3
Hans Olsson Avatar answered Oct 18 '22 22:10

Hans Olsson