2012-10-15

Calculating Age in C# (Subtract DateTime from DateTime?)

So far I have seen many attempts from many people to determine the age of a person in reference to a given date in many languages. But actually the examples I have seen in C# were the strangest and partially buggiest attempts I have seen.
Maybe the main problem is, that C#'s DateTime class does not offer a direct method to subtract a DateTime from a DateTime.
This is one particular attempt I have seen these days (trying to debug some age related calculation):
- Given are birthdate A and reference date B
- let integer C be B.Year - A.Year
- decrease C by one based on some strange 3-line formula doing something with A.month, A.day, B.month and B.day
... This may work if the Dates A and B are accidently chosen correctly but basically what happend in most cases I tested this calculation with resulted in an age beeing 1 year lower than it actually was.
So, if you ever have to determine the age of someone based on a reference date, just use the maybe simplest approach to solve this problem using an extension to DateTime:

     public static class DateTimeExtensions
    {
        public static int GetAge(this DateTime birthdate, DateTime referencedate)
        {
            DateTime x = referencedate.AddTicks(-1 * birthdate.Ticks);
            return x.Year;
        }
    }

That way if you want to know someones Age based on a reference date... as in, how old will Person X (born July 4th, 1950) be at January, 1st 2012 you can do
    int age = new DateTime(1950,7,4).GetAge(new DateTime(2012,1,1));