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

huerita37Asked:
Who is Participating?
 
mohammad827Connect With a Mentor Commented:
DateDiff(DateInterval.Month, Now, DOB)
Above should give you difference in month.
Divide it by 12 and you will get year and month
0
 
RouchieCommented:
Timespan is what you need, you can go right down to milliseconds!

http://msdn.microsoft.com/en-us/library/system.timespan.aspx
0
 
Kumaraswamy RCommented:
0
 
RouchieCommented:
Timespan gives you all of that without any division or further math's being required.
0
 
huerita37Author Commented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.