Calculate age in years

I have a .Net web page that has a datepicker that gives date in mm/dd/yyyy
On SeletedDateChanged I calculate the age in years with the code below...

I suspect this has holes in the logic as it is just getting the years without accounting for the actual date

            Dim curDate As DateTime = DateTime.Now
            Dim curyear As Int32 = curDate.Year
            Dim birthdate As DateTime = txtBirthDate.SelectedDate
            Dim birthYear As Int32 = birthdate.Year
            Dim yrsAge As Int32 = curyear - birthYear
            txtAge.Text = CStr(yrsAge)

Open in new window

Larry Bristersr. DeveloperAsked:
Who is Participating?
Éric MoreauSenior .Net ConsultantCommented:
You are only accounting for the year (instead of the full date). One way I like is:

dim totalYears = (DateTime.Today - new DateTime(2007, 03, 11)).TotalDays / 365.2425

Open in new window

Dustin SaundersDirector of OperationsCommented:
You've basically got it, just need check if the day is higher than the day of birth.

Alternative method
DateTime birthday = new DateTime(1985, 1, 9);
int age = DateTime.Now.Year - birthday.Year;
if (birthday > DateTime.Now.AddYears(-age))

Open in new window

Larry Bristersr. DeveloperAuthor Commented:
That works!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.