Difference between two dates and working out if the person is over 18 or under 18 c#

I'm going to have two dates. A Date of birth And a Date of event

I want to calculate if the time passed between date of birth and event date is less than or greater than 18 years. The event date will always be greater than the date of birth.

If under 18 then true else false.

EG: DOB 29/02/1976. Event Date 29/12/2017

The person here is over 18!

I'm not sure if using DateAdd or DateDiff is the best approach - or even if using DateTime.Days && DateTime.Months etc

Jon Skeet
people
quotationmark

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

people

See more on this question at Stackoverflow