Solved

# Calculate current age in years and months

Posted on 2013-05-22
Medium Priority
410 Views
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
age -= 1
End If

formatAge = age.ToString()

End Function
``````
0
Question by:huerita37
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 25

Expert Comment

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

http://msdn.microsoft.com/en-us/library/system.timespan.aspx
0

LVL 4

Accepted Solution

ID: 39189873
DateDiff(DateInterval.Month, Now, DOB)
Above should give you difference in month.
Divide it by 12 and you will get year and month
0

LVL 29

Expert Comment

ID: 39189892
0

LVL 25

Expert Comment

ID: 39189893
Timespan gives you all of that without any division or further math's being required.
0

Author Closing Comment

ID: 39189917
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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
###### Suggested Courses
Course of the Month12 days, 11 hours left to enroll