Calculating Age from Date of Birth in VB.NET
It’s quite common to need to calculate a person’s age from the date of birth they have entered. Here’s the quick and easy way of doing it:
strDOB = txtDateOfBirth.Text
Dim intAge As Integer
intAge = Math.Floor(DateDiff(DateInterval.Month, DateValue(strDOB), Now()) / 12)
lblAge.Text = intAge
In this example the date of birth data is captured in a TextBox control called txtDateOfBirth. The DateDiff function calculates the difference between two dates. The arguments are the interval to focus on (here months), the first date (here the date of birth) and the second date (here the current date). The date of birth is expressed as DateValue(strDOB) to convert the string to a date format. This is then divided by 12 to give the age in years as a decimal. Finally, the introductory Math.Floor is used to round the number down to the nearest whole number.
| Print article | This entry was posted by admin on March 8, 2010 at 3:46 pm, and is filed under DateDiff(), DateInterval, DateValue(), Math.Floor(), Now(), VB.NET. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

