Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

javascript - Checking if date belongs to array of dates

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...