Compute age using dtpicker transfer result to textbox

liam

Member
Joined
Jun 8, 2004
Messages
23
Programming Experience
Beginner
here's my code but it doesn't work.. hope someone can help me out...

Private Sub dtpBDate_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpBDate.ValueChanged

Dim a As Date = Date.Today.ToShortDateString

Dim b As Date = dtpBDate.Value.ToShortDateString

tbAge.Text = b.Subtract(a)

End Sub

 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
Here are two functions which may help:

VB.NET:
'returns a string that show years, months and days
Public Function CalculateAge(ByVal BirthDate As Object) As String
    Dim intYear As Integer, intMonth As Integer, intDay As Integer
    Dim dtTemp As Date

    If Not IsDate(BirthDate) Then Exit Function

    dtTemp = CDate(BirthDate)
    If dtTemp > Now Then Exit Function

    intYear = dtTemp.Year
    intMonth = dtTemp.Month
    intDay = dtTemp.Day
    intYear = Date.Now.Year - intYear
    intMonth = Date.Now.Month - intMonth
    intDay = Date.Now.Day - intDay

    If intDay < 0 Then
        Select Case dtTemp.Month
            Case 1, 3, 5, 7, 8, 10, 12
                intDay = 31 - Math.Abs(intDay)
            Case 4, 6, 9, 11
                intDay = 30 - Math.Abs(intDay)
            Case 2
                If dtTemp.Year Mod 4 = 0 Then
                    intDay = 29 - Math.Abs(intDay)
                Else
                    intDay = 28 - Math.Abs(intDay)
                End If
        End Select
        intMonth = intMonth - 1
    End If

    If intMonth < 0 Then
        intMonth = 12 - Math.Abs(intMonth)
        intYear = intYear - 1
    End If

    Return IIf(intYear <> 0, intYear & " Years ", "") & _
           IIf(intMonth <> 0, intMonth & " Months ", "") & _
           IIf(intDay <> 0, intDay & " Days", "")

End Function

'returns only years
Public Function CalcAge(ByVal BirthDate As Object) As Long
    If Not IsDate(BirthDate) Then Exit Function
    Dim dtTemp As Date
    dtTemp = CDate(BirthDate)
    If dtTemp > Now Then Exit Function
    Return DateDiff("yyyy", dtTemp, Date.Now) + (DateSerial(Year(Date.Now), _
                     Month(dtTemp), dtTemp.Day) >= Date.Now)
End Function

To get better support you may want to include what is supposed to happen :)
 
Top Bottom