jQuery UI, Calendar, find out if date given is over 2 years old
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?
var selectedDate = new Date('01/27/2004');
selectedDate.setFullYear(selectedDate.getFullYear()+2);
var moreThan2YearsOld = selectedDate < new Date();
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
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;
精彩评论