8

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?

James
  • 80,725
  • 18
  • 167
  • 237
Ramakrishna
  • 203
  • 1
  • 5
  • 13

9 Answers9

18

hope this is what you are looking for

public bool CheckDate(DateTime date1, DateTime date2)
{
    return date1.AddYears(-18) < date2;
}
Rob
  • 26,989
  • 16
  • 82
  • 98
Bhavik Goyal
  • 2,786
  • 6
  • 23
  • 42
2

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; 
}
James
  • 80,725
  • 18
  • 167
  • 237
1

Use TimeSpan structure.

TimeSpan span= dateSecond - dateFirst;
int days=span.Days;
//or
int years = (int) (span.Days / 365.25);
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
0
DateTime zeroTime = new DateTime(1, 1, 1);

DateTime a = new DateTime(2008, 1, 1);
DateTime b = new DateTime(2016, 1, 1);

TimeSpan span = b - a;
// because we start at year 1 for the Gregorian 
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1; 

Console.WriteLine("Years elapsed: " + years); 

Refrence Link

Community
  • 1
  • 1
Durgesh Pandey
  • 2,314
  • 4
  • 29
  • 43
0

Try this.... Using this you can get the exact no of years between two days. Only you need to do is divide the date difference by 365.25

 TimeSpan span = DateTime.Parse(To_Date) - DateTime.Parse(From_Date);
 int years = (int)(span.Days / 365.25);
0

Check the TimeSpan structure: http://msdn.microsoft.com/en-us/library/system.timespan.aspx

CodeZombie
  • 5,367
  • 3
  • 30
  • 37
0

Use Timespan:

TimeSpan day = 03-12-2011 - 03-12-1983;
                double year = day.TotalDays / 365.25;

                if (year > 18)
                {

                }

Maybe instead of 03-12-2011 you should use DateTime.Now

Oedum
  • 796
  • 2
  • 9
  • 28
0

Here's a method to check if the age is more than 18:

    private bool IsMoreThan18(DateTime from, DateTime to)
    {
        int age = to.Year - from.Year;
        if (from > to.AddYears(-age)) age--;
        return age >= 18;
    }
JiBéDoublevé
  • 4,124
  • 4
  • 36
  • 57
-1

Create two DateTime objects and substract them from eachother. The result is a DateTime object aswel:

DateTime dt = new DateTime(2011, 12, 03);
DateTime dt2 = new DateTime(1983, 12, 03);
DateTime dt3 = dt - dt2;

Now you can check dt3.Year for the number of years between them

Michiel van Vaardegem
  • 2,260
  • 20
  • 35