Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate an age based on a birthday [duplicate]

Tags:

Possible Duplicate:
How do I calculate someone's age based on a DateTime type birthday?

I want to write an ASP.NET helper method which returns the age of a person given his or her birthday.

I've tried code like this:

public static string Age(this HtmlHelper helper, DateTime birthday) {     return (DateTime.Now - birthday); //?? } 

But it's not working. What is the correct way to calculate the person's age based on their birthday?

like image 647
nacho10f Avatar asked Feb 03 '10 19:02

nacho10f


People also ask

Can Excel calculate age based on birthdate?

Simply by subtracting the birth date from the current date. This conventional age formula can also be used in Excel. The first part of the formula (TODAY()-B2) returns the difference between the current date and date of birth is days, and then you divide that number by 365 to get the numbers of years.

What is the fastest way to calculate age from date of birth?

The method of calculating age involves the comparison of a person's date of birth with the date on which the age needs to be calculated. The date of birth is subtracted from the given date, which gives the age of the person. Age = Given date - Date of birth.


2 Answers

Stack Overflow uses such a function to determine the age of a user.

How do I calculate someone's age based on a DateTime type birthday?

The given answer is

DateTime now = DateTime.Today; int age = now.Year - bday.Year; if (now < bday.AddYears(age))      age--; 

So your helper method would look like:

public static string Age(this HtmlHelper helper, DateTime birthday) {     DateTime now = DateTime.Today;     int age = now.Year - birthday.Year;     if (now < birthday.AddYears(age))          age--;      return age.ToString(); } 

Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.

public static int GetAge(DateTime reference, DateTime birthday) {     int age = reference.Year - birthday.Year;     if (reference < birthday.AddYears(age))         age--;      return age; } 
like image 55
Pierre-Alain Vigeant Avatar answered Oct 22 '22 12:10

Pierre-Alain Vigeant


Another clever way from that ancient thread:

int age = (     Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -      Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000; 
like image 39
Rubens Farias Avatar answered Oct 22 '22 12:10

Rubens Farias