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