I would like to compare 2 dates to confirm that the number of years between is >= 18
. For example, if my 2 dates are 03-12-2011
and 03-12-1983
then this should pass validation, however, if my 2 dates are 03-12-2011
and 03-12-1995
then this should fail validation.
Can anyone help me?
hope this is what you are looking for
public bool CheckDate(DateTime date1, DateTime date2)
{
return date1.AddYears(-18) < date2;
}
I re-jigged your question title & description to make it a bit more clear. From what I gathered from your original post you are looking for an Age Verification function. Here is what I would do:
function VerifyAge(DateTime dateOfBirth)
{
DateTime now = DateTime.Today;
int age = now.Year - dateOfBirth.Year;
if (now.Month < dateOfBirth.Month || (now.Month == dateOfBirth.Month && now.Day < dateOfBirth.Day))
age--;
return age >= 18;
}
Use TimeSpan
structure.
TimeSpan span= dateSecond - dateFirst;
int days=span.Days;
//or
int years = (int) (span.Days / 365.25);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With