Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the number of years between 2 dates?

Tags:

c#

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?

like image 986
Ramakrishna Avatar asked Nov 25 '11 12:11

Ramakrishna


3 Answers

hope this is what you are looking for

public bool CheckDate(DateTime date1, DateTime date2)
{
    return date1.AddYears(-18) < date2;
}
like image 99
Bhavik Goyal Avatar answered Nov 10 '22 07:11

Bhavik Goyal


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; 
}
like image 27
James Avatar answered Nov 10 '22 08:11

James


Use TimeSpan structure.

TimeSpan span= dateSecond - dateFirst;
int days=span.Days;
//or
int years = (int) (span.Days / 365.25);
like image 29
KV Prajapati Avatar answered Nov 10 '22 06:11

KV Prajapati