ASP 101 - Active Server Pages 101 - Web06
The Place ASP Developers Go!

Windows Technology Windows Technology
15 Seconds
ASP 101
ASP Wire
VB Forums
VB Wire
internet.commerce internet.commerce
Partners & Affiliates
ASP 101 is an site
ASP 101 is an site
Internet News
Small Business
Personal Technology

Corporate Info
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash

 Top ASP 101 Stories Top ASP 101 Stories
Connections, Commands, And Procedures
What is ASP?
VBScript Classes: Part 1 of N

Cache commonly used values in application variables
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates

Quick Tips

How To Calculate Age

Determining a person's age given their date of birth seems simple enough, but I get a lot of email from people who can't seem to get the code working as it should.

Most of the code I get sent usually looks something like this:

intAge = DateDiff(DateInterval.Year, dtBirthDate, Today())

or the slightly less error-prone:

intAge = DateDiff(DateInterval.Month, dtBirthDate, Today()) \ 12

The problem with both of these is in the way the DateDiff function works. If the person's birthday has not yet occurred this year, using either of the options above will lead to an incorrect result. Depending on if you're in the same month as the birthdate, one or both of the above will give an age which makes the person seem a year older then they actually are.

Here's a function which compensates for this common mistake. It checks if the person's birthday has already passed this year and adjusts the resulting age accordingly.

Function Age(ByVal dtBirthDate As Date) As Integer
    Dim intAge As Integer
    intAge = DateDiff(DateInterval.Year, dtBirthDate, Today())
    If Today() < DateSerial(Year(Today()), Month(dtBirthDate), Day(dtBirthDate)) Then
        intAge = intAge - 1
    End If
    Return intAge
End Function

The function is not difficult, but it can be a little confusing to write yourself. Luckily you don't have to... just use ours.

Previous      Show All Tips      Next

If you have a tip you would like to submit, please send it to:

Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback
The Network for Technology Professionals



Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers