Age in years with decimal precision, given the date and time

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

I want the exact age, for example, 40.69 years

+4
source share
6 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 next birthday, so it will correctly cope with leap years.

The fractional part is linear throughout the year (and does not take into account different lengths of months), which, apparently, makes the 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); 
+10
source

This will be an approximate calculation:

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

By the way: see also this question about stack overflow: How to calculate the age of people in C #?

+5
source

Example:

  DateTime bd = new DateTime(1999, 1, 2); TimeSpan age = DateTime.Now.Subtract(bd); Console.WriteLine(age.TotalDays / 365.25); 
+1
source

The 40-year-old is quite simple. But to get the exact decimal point, I'm not sure how you translate the rest of the age into a decimal number. You see that age is expressed in years, months, days, hours, seconds. And the calculation is not so simple. You have to deal with anniversary dates. For example, if someone was born on January 31, when they are 1 month old? The answer is March 1st. But in a few years it is in 28 days and a few years later in 29 days. Here is the javascript implementation I was trying to handle.

But I believe that a decimal number can express the number of days from the last birthday anniversary divided by the number of days until the next anniversary. And if you want to clarify, you can do it in seconds using the same principle.

But I think this is a bad idea of ​​age. Usually we usually do not imagine such an age.

And make sure your dates are in the same time zone for your comparisons.

+1
source

You can do it:

 Console.WriteLine(DateTime.Now.Date.Subtract(new DateTime(1980, 8, 1)).TotalDays / 365.25); 
0
source

how much error is allowed in the fractional part? exact age will be

31 years, 10 days, 3 hours, etc. depending on the desired accuracy.

0
source

All Articles