Jacque Scott
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
calculating of age by year,months and day in vb.net
http://www.codeproject.com/Questions/432219/calculating-of-age-by-year-months-and-day-in-vb-ne
http://www.codeproject.com/Questions/432219/calculating-of-age-by-year-months-and-day-in-vb-ne
Timespan gives you all of that without any division or further math's being required.
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.Mont h, dt1, dt2)
Dim Years As Long = Diff \ 12
Months = Diff - Years * 12
formatAge = Years & " y " & Months & " m "
End Function
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.Mont
Dim Years As Long = Diff \ 12
Months = Diff - Years * 12
formatAge = Years & " y " & Months & " m "
End Function
http://msdn.microsoft.com/en-us/library/system.timespan.aspx