Age in years with decimal precision given a datetime

前端 未结 6 1960
-上瘾入骨i
-上瘾入骨i 2021-01-06 03:37

How can I get the age of someone given the date of birth in a C# datetime.

I want a precise age like 40.69 years old

6条回答
  •  心在旅途
    2021-01-06 03:57

    This will calculate the exact age. The fractional part of the age is calculated relative to the number of days between the last and the next birthday, so it will handle leap years correctly.

    The fractional part is linear across the year (and doesn't take into account the different lengths of the months), which seems to make most sense if you want to express a fractional age.

    // birth date
    DateTime birthDate = new DateTime(1968, 07, 14);
    
    // get current date (don't call DateTime.Today repeatedly, as it changes)
    DateTime today = DateTime.Today;
    // get the last birthday
    int years = today.Year - birthDate.Year;
    DateTime last = birthDate.AddYears(years);
    if (last > today) {
        last = last.AddYears(-1);
        years--;
    }
    // get the next birthday
    DateTime next = last.AddYears(1);
    // calculate the number of days between them
    double yearDays = (next - last).Days;
    // calcluate the number of days since last birthday
    double days = (today - last).Days;
    // calculate exaxt age
    double exactAge = (double)years + (days / yearDays);
    

提交回复
热议问题