0

Hay Guys, I'm using the bog standard Calendar from the jQuery UI system. The result shown (after a user clicks a date) is MM/DD/YYYY.

I want to check that this date is not old than 2 years old

ie

say a user picks

01/27/2004

this should say that the date is older than 2 years. However,

12/25/2008

should pass the test.

any ideas?

dotty
  • 40,405
  • 66
  • 150
  • 195

3 Answers3

3
var selectedDate = new Date('01/27/2004');
selectedDate.setFullYear(selectedDate.getFullYear()+2);

var moreThan2YearsOld = selectedDate < new Date();
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
2

DateDiff returns the difference between dates in milliseconds:

function DateDiff(date1, date2){
    return Math.abs(date1.getTime()-date2.getTime());
}

... and if this is bigger than the number of microseconds equivalent to two years ...

date1 = new Date("01/27/2004");
date2 = new Date(); // now

DateDiff(date1, date2);
// => 185717385653
//    31536000000 // == two years

The number of milliseconds per years is 31536000000.

More on that matter: What's the best way to calculate date difference in Javascript

Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310
1

You can use the getFullYear function to check this.

You could use something like (untested):

var date = new Date($('#calendarId').val());
var today = new Date();
var moreThan2Years = (today.getFullYear() - date.getFullYear()) > 2;
Fermin
  • 34,961
  • 21
  • 83
  • 129