Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

ASP.NET: Calculate a person's age from their date of birth

From Wiki

Jump to: navigation, search


Summary: Calculate a person's age from their date of birth

Need help with ASP.NET? Come and ask a question in our ASP.NET Forum

Here's a simple method of calculating a person's age based on their date of birth:

  1. Partial Class Default1
  2.     Inherits System.Web.UI.Page
  3.  
  4.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  5.         Response.Write(GetMyAge(New Date(1979, 7, 25)))
  6.     End Sub
  7.  
  8.     Private Function GetMyAge(ByVal BirthDate As Date) As Integer
  9.         Return Math.Floor(DateTime.Today.Subtract(BirthDate).TotalDays / 365.25)
  10.     End Function
  11.  
  12. End Class

Output:


This Hack is part of the ASP.NET Hacks collection

Oh dear - the above example doesn't work! Dividing by 365.25 gives an approximation to someone's age, but that doesn't really cut the mustard with me.

For example: If your date of birth is 01 Jan 2001 and today is 01 Jan 2002, then 365 days have passed. 365 / 365.25 = 0.99932, Math.Floor rounds down, so we say you're zero years old when you're actually one.

Except when a multiple of four leap years have passed, you get rounding errors on your birthday: the one day you really want your age to be reported correctly. :-)

Working it out the long way round seems a bit more of a pain in the ass, but not only does it perform only integer comparisons (and thus avoids slow floating point division), but also gives the right answer:

  1. public static int GetAge(DateTime dateOfBirth, DateTime asOfDate)
  2. {
  3.     int age = asOfDate.Year - dateOfBirth.Year;
  4.  
  5.     if (asOfDate.Month < dateOfBirth.Month || (asOfDate.Month == dateOfBirth.Month && asOfDate.Day < dateOfBirth.Day))
  6.         age--;
  7.  
  8.     return age;
  9. }

486 Rating: 3.2/5 (33 votes cast)