C# calculate accurate age

前端 未结 14 1802
攒了一身酷
攒了一身酷 2020-12-15 11:01

anyone know how to get the age based on a date(birthdate)

im thinking of something like this

string age = DateTime.Now.GetAccurateAge();
14条回答
  •  甜味超标
    2020-12-15 11:55

    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;
    

提交回复
热议问题