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));



2 comments:

  1. "Maybe the main problem is, that C#'s DateTime class does not offer a direct method to subtract a DateTime from a DateTime."

    This statement is incorrect. It is possible to subtract DateTime(s) in C#.

    DateTime date1 = new DateTime(1950, 7, 4);
    DateTime date2 = new DateTime(2012, 1, 1);
    TimeSpan diff = date2.Subtract(date1);
    DateTime date0 = new DateTime().Add(diff);
    int yearsOld = date0.Year - 1; // to account for the min DateTime() of 1/1/0001

    http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx

    ReplyDelete
    Replies
    1. Yes, I know that you can ".Subtract(DateTime)" from a DateTime. But by my statement I explicitly pointed out, that there is no DIRECT method to get to the result. With direct method I mean that you can't just say date1.subtract(date2).Year... Subtracting a DateTime always returns a TimeSpan, so you always end up creating a new DateTime with which you can work.

      Delete