Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Age in years with decimal precision given a datetime

Tags:

c#

datetime

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

like image 385
Blankman Avatar asked Dec 02 '22 08:12

Blankman


2 Answers

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);
like image 199
Guffa Avatar answered Dec 04 '22 21:12

Guffa


This would be an approximative calculation:

 TimeSpan span = DateTime.Today.Subtract(birthDate);
 Console.WriteLine( "Age: " + (span.TotalDays / 365.25).toString() );

BTW: see also this question on Stack Overflow: How do I calculate someone’s age in C#?

like image 41
splattne Avatar answered Dec 04 '22 22:12

splattne