Calculate Age

Calculating someone's age is pretty straightforward, and here's how! In order for the code to work, you need a DateTime object called BirthDate containing the birthday.

C#

// get the difference in years
int years = DateTime.Now.Year - BirthDate.Year;
// subtract another year if we're before the
// birth day in the current year
if (DateTime.Now.Month < BirthDate.Month ||
    (DateTime.Now.Month == BirthDate.Month &&
    DateTime.Now.Day < BirthDate.Day))
    years--;

VB.NET

' get the difference in years
Dim years As Integer = DateTime.Now.Year - BirthDate.Year
' subtract another year if we're before the
' birth day in the current year
If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then
    years = years - 1
End If

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“God could create the world in six days because he didn't have to make it compatible with the previous version.”