Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

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:

  1. 28


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.4/5 (5 votes cast)