## 4 replies

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

• kmcnet

Member

285 Points

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

• b471code3

Star

9197 Points

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

Kentico MVP  Remember to mark as answer.
• Ramesh T

Contributor

4627 Points

1036 Posts

### Re: Calculating Age

Feb 16, 2012 06:49 PM|Ramesh T|LINK

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```
• venkatmca008

Participant

1177 Points

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