Showing posts with label dropdownlists. Show all posts
Showing posts with label dropdownlists. Show all posts

Saturday, March 31, 2012

String to Date conversion

Im trying to convert the input of several dropdownlists into a Date, but I can get an error and dont know how to convert these fields to a date type...
This is the code:
Dim BirthDate As DateTime = CType(ddlDay.SelectedValue + ddlMonth.SelectedValue + ddlYear.SelectedValue, Date)
And now im here anyways :p ...how can I calculate someones age when I have his birth date?

It would probably be best if you keep the two types the same. Try using this:

Dim BirthDate As DateTime = CType(ddlDay.SelectedValue & "/" & ddlMonth.SelectedValue & "/" & ddlYear.SelectedValue, DateTime)


Try using something like this, for the calculation (assuming a sub, based on a button's click event):

Sub getDiff(Source as Object, E as EventArgs)
Dim myBirth as DateTime
Dim sDate as String
Dim Age As Integer
sDate=ddMonth.SelectedItem.Value & "/" & ddDay.SelectedItem.Text & "/" & ddYear.SelectedItem.Text
myBirth=cDate(sDate)
Age=DateTime.Now.Year - myBirth.Year
If DateTime.Now.Month < myBirth.Month Or (DateTime.Now.Month = myBirth.Month And DateTime.Now.Day < myBirth.Day) Then
Age = Age - 1
End If
lblDate.text="Age=" & Age.ToString
End Sub

Check out full code sample:
http://aspnet101.com/aspnet101/aspnet/codesample.aspx?code=calcage


Hi Peter Smith,

Give the following a try. Example:

Dim tempAsString = ddlDay.SelectedValue + "/" + ddlMonth.SelectedValue + "/" + ddlYear.SelectedValue
Dim birthDateAs DateTime = DateTime.Parse(temp)

The following function can be used to calculate Age, given a BirthDate. Example:

Public Shared Function Age(ByVal dateOfBirth As DateTime) As Integer
If DateTime.Today.Month < dateOfBirth.Month Or DateTime.Today.Month = dateOfBirth.Month And DateTime.Today.Day < dateOfBirth.Day Then
Return DateTime.Today.Year - dateOfBirth.Year - 1
Else
Return DateTime.Today.Year - dateOfBirth.Year
End If
End Function

Hope this helps.