Library code snippets

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

Comments

  1. 17 Sep 2007 at 07:47

    Alternative solution:

    DateTime comparisonDate = new DateTime(_birthday.Year, DateTime.Now.Month, DateTime.Now.Day);

     

    int age = (comparisonDate.Date < _birthday.Date) ?
    DateTime.Now.Year - _birthday.Year - 1:
    DateTime.Now.Year - _birthday.Year;

  2. 10 Aug 2006 at 16:20

    Developer Fusion Bot wrote:
    This thread is for discussions of Calculate Age

    Description of calculate age and working principle

  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Calculate Age.

Leave a comment

Sign in or Join us (it's free).

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

Related podcasts

  • A Practical Look at Silverlight 2 Part 1

    Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...

Events coming up

  • Dec 9

    GL.net Group Meeting - December 2009

    Gloucester, United Kingdom

    The beginning of this year holiday season will belong to mocks. Ronnie and Stephen will take us for a tour around exciting world of unit testing.

We'd love to hear what you think! Submit ideas or give us feedback