Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Mar 10, 2012 09:40 AM by limryan3
Feb 16, 2012 09:28 PM|LINK
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.
Feb 16, 2012 10:47 PM|LINK
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"
Label1.Text = "over 18"
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.
Feb 16, 2012 10:49 PM|LINK
You could calculate like this
Dim now = DateTime.Today
Dim YearsOld = now.Year - DOB.Year
If DOB > now.AddYears(-YearsOld) Then YearsOld = YearsOld - 1
Feb 16, 2012 11:33 PM|LINK
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
TextBox1.Text = years
Mar 10, 2012 09:40 AM|LINK
Thanks for your code snipset. I really helps me alot.