## 4 replies

Last post Mar 10, 2012 09:40 AM by limryan3

Participant

1090 Points

652 Posts

### Calculating Age

Hello Everyone and thanks for your help in advance.  I am working on an application that needs to determine whether a person has passed their 18th birthday.  I tried the following code:

Dim DOB As Date = "3/25/1994"

Dim TodaysDate As Date = Now().ToShortDateString

YearsOld = DateDiff(DateInterval.Month, DOB, TodaysDate)

However, when I run this code today (2/16/2012), it returns the number 18.  Obviously, this person's 18th birthday has not yet passed so this code will not work.  I'm not sure what the problem is.  Any help would be greatly appreciated.

Star

13877 Points

2598 Posts

### Re: Calculating Age

First off, not sure how you got that code to return 18, it returns 215.  Secondly, if you truely want to see if they are over 18 then you should try something like this:

```Dim eightTeenYearsAgo As Date = DateTime.Now.AddYears(-18)
If DOB > eightTeenYearsAgo Then
Label1.Text = "under 18"
Else
Label1.Text = "over 18"
End If```

The problem before was it was rounding the 17 years 11 months to 18 years because the DateDiff() method returns a Long which is considered an integer.

Contributor

5079 Points

821 Posts

### Re: Calculating Age

Hello Mate,

You could calculate like this

```Dim now = DateTime.Today
Dim YearsOld = now.Year - DOB.Year
If DOB > now.AddYears(-YearsOld) Then YearsOld = YearsOld - 1```
• Edited by Ramesh T on Feb 16, 2012 10:51 PM
• Edited by Ramesh T on Feb 16, 2012 10:52 PM

Participant

1810 Points

341 Posts

### Re: Calculating Age

HI TRY THIS....

```Dim years As Integer = DateTime.Now.Year - Calendar1.SelectedDate.Year
If DateTime.Now.Month < Calendar1.SelectedDate.Month Or (DateTime.Now.Month = Calendar1.SelectedDate.Month And DateTime.Now.Day < Calendar1.SelectedDate.Day) Then
years = years - 1
End If
TextBox1.Text = years```
A.Venkatesan
Microsoft Certified Professional
Please mark the replies as answers if they help or unmark if not.