Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
101
rated 0 times [  107] [ 6]  / answers: 1 / hits: 32563  / 11 Years ago, wed, june 12, 2013, 12:00:00

I'm trying to check if a date from a jQuery UI datepicker belongs to an array of dates that are holidays. Can't figure out what I'm doing wrong :(



var holidayArray2013 = [new Date('October 3, 2013 00:00:00 GMT+0200'), new Date('December 25, 2013 00:00:00 GMT+0100'), new Date('December 26, 2013 00:00:00 GMT+0100')];
var DateOfOrder = $('#datepicker').datepicker('getDate');
if ($.inArray(DateOfOrder, holidayArray2013) > -1) {
console.log(is holiday);
}


edit: console.log(DateOfOrder); returns Thu Oct 03 2013 00:00:00 GMT+0200 just like holidayArray2013[0] but $.inArray(DateOfOrder, holidayArray2013) still returns -1


More From » jquery

 Answers
10

You're getting a false negative because comparing 2 date objects compares their references and not their values as you perhaps expected.



There are a few options, you could store the result of Date.getTime() in your array which is just a numerical representation of the date:



var holidayArray2013 = [
new Date('October 3, 2013 00:00:00 GMT+0200').getTime(),
new Date('December 25, 2013 00:00:00 GMT+0100').getTime(),
new Date('December 26, 2013 00:00:00 GMT+0100').getTime()];


And then compare that:



var DateOfOrder = n$('#datepicker').datepicker('getDate').getTime();
if ($.inArray(DateOfOrder, holidayArray2013) > -1) ...


This works fine, as demonstrated here: http://jsfiddle.net/rRJer/



If, however you are constrained to not changing the holiday array you could loop to try to locate the right date value:



var isHoliday = false;
for(var i=0;i<holidayArray2013.length;i++){
if(holidayArray2013[i].getTime() == DateOfOrder.getTime()){
isHoliday = true;
break;
}
}


Demo is here: http://jsfiddle.net/3R6GD/


[#77663] Tuesday, June 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sandra

Total Points: 708
Total Questions: 100
Total Answers: 84

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
sandra questions
Tue, Jun 30, 20, 00:00, 4 Years ago
Sun, May 31, 20, 00:00, 4 Years ago
Wed, May 20, 20, 00:00, 4 Years ago
Fri, May 31, 19, 00:00, 5 Years ago
;