views:

196

answers:

3

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?

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

var moreThan2YearsOld = selectedDate < new Date();
David Hedlund
Thanks David, works a treat!
dotty
+2  A: 

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: http://stackoverflow.com/questions/327429/whats-the-best-way-to-calculate-date-difference-in-javascript

The MYYN
+1  A: 

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