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.TextDim 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.