Link to home
Start Free TrialLog in
Avatar of Jacque Scott
Jacque ScottFlag for United States of America

asked on

Calculate current age in years and months

I have the following code that I had found which finds the persons current age from their date of birth.  The only problem is that it only shows the age in years.  I also need the months.  What can I add to also show the months?

    Protected Function formatAge(ByVal DOB As DateTime) As String

        Dim now As DateTime = DateTime.Now
        DOB = Convert.ToDateTime(ClientDOB.Text)
        Dim age As Integer = now.Year - DOB.Year
        If now < DOB.AddYears(age) Then
            age -= 1
        End If

        formatAge = age.ToString()

    End Function

Open in new window

Avatar of Rouchie
Rouchie
Flag of United Kingdom of Great Britain and Northern Ireland image

Timespan is what you need, you can go right down to milliseconds!

http://msdn.microsoft.com/en-us/library/system.timespan.aspx
ASKER CERTIFIED SOLUTION
Avatar of mohammad827
mohammad827
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Kumaraswamy R
Timespan gives you all of that without any division or further math's being required.
Avatar of Jacque Scott

ASKER

I was able to find the correct answer with using DateInterval.

Here is what I did:

 Protected Function formatAge(ByVal DOB As DateTime) As String

        Dim dt1, dt2 As Date
        dt1 = DOB
        dt2 = now
        Dim Months As Long
        Dim Diff As Long = DateDiff(DateInterval.Month, dt1, dt2)
        Dim Years As Long = Diff \ 12
        Months = Diff - Years * 12
        formatAge = Years & " y  " & Months & " m "

    End Function