- 28
ASP.NET: Calculate a person's age from their date of birth
From Wiki
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:
- Partial Class Default1
- Inherits System.Web.UI.Page
- Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
- Response.Write(GetMyAge(New Date(1979, 7, 25)))
- End Sub
- Private Function GetMyAge(ByVal BirthDate As Date) As Integer
- Return Math.Floor(DateTime.Today.Subtract(BirthDate).TotalDays / 365.25)
- End Function
- 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:
- public static int GetAge(DateTime dateOfBirth, DateTime asOfDate)
- {
- int age = asOfDate.Year - dateOfBirth.Year;
- if (asOfDate.Month < dateOfBirth.Month || (asOfDate.Month == dateOfBirth.Month && asOfDate.Day < dateOfBirth.Day))
- age--;
- return age;
- }


