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

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

  • Nov 18

    15 Minutes of Fame

    Dresher, United States

    This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.

Want to stay in touch with what's going on? Follow us on twitter!