tags:

views:

455

answers:

4

Duplicate

How Can I calculate Someone's Age in C#?

I have a datetime variable that represents the date of birth of a user.

How can I get the age in years from this?

Update I want a precise birthday, so 30.45 years or something.

A: 

You can try with (in Vb):

    Dim dateOfBirth As Date

    Now.Subtract(dateOfBirth).TotalDays \ 365

\ is an Integer division in Vb, I do not know if it has a correspondant in C#.

A: 

Try the following (assuming the date of birth is stored in dtDOB):

public int getAgeInYears {
  TimeSpan tsAge = DateTime.Now.Subtract(dtDOB);

  return new DateTime(tsAge.Ticks).Year - 1;
}
Mark Pim
This wrong! DateTime.Subtract() returns a Timespan, not a DateTime.
M4N
A: 

Stolen from the answer to Jeff's question:

DateTime now = DateTime.Now;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
Nathan DeWitt