9

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.

Community
  • 1
  • 1

3 Answers3

6

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
  • 9,898
  • 7
  • 40
  • 59
4

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
  • 6,511
  • 8
  • 46
  • 66
1

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#.