The example you gave is a reasonably easy one - but there are harder ones. Consider this:
- Date of birth: Feb 29th 1976
- Event date: Feb 28th 1994
If you add 18 years to the date of birth, you'll get Feb 28th 1994 - the event date. That suggests the person is 18 years old.
If you subtract 18 years from the event date, you'll get Feb 28th 1976 (before the person's birthday). That suggests the person isn't 18 years old.
I suspect in almost all cases, you'd consider that the person celebrates their birthday on Feb 28th in non-leap years. So the code would be:
var adult = birthDate.AddYears(18) <= eventDate;
Make sure both values are just dates without any time-of-day though.
The core .NET libraries don't provide any way of finding the period between two DateTime
values. You can find the TimeSpan
, but that's not the same thing, and isn't useful for calendrical calculations. (You can't tell whether a TimeSpan
of 30 days is a whole month or not for example, because it depends on the context.)
My Noda Time library does provide this facility:
var birthDate = new LocalDate(1976, 2, 29);
var eventDate = new LocalDate(1994, 2, 28);
var period = Period.Between(birthDate, eventDate);
var adult = period.Years >= 18;
Console.WriteLine(period); // P18Y
... but you can easily accomplish what you need in DateTime
in this case. (I'd advise using Noda Time anyway if you have other date/time scenarios, just on the principle that it's designed to make date/time work easier to get right.)