本文介绍了检查是否日期属于日期的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,以检查是否从jQuery UI的日期选择器的日期所属日期是假期的数组。想不通我做错了什么:(

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");
}

编辑:的console.log(DateOfOrder); 收益周四2013年10月3日00:00:00 GMT + 0200 就像 holidayArray2013 [0] ,但 $。inArray(DateOfOrder,holidayArray2013)仍然返回 -1

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

推荐答案

您会得到一个假阴性,因为比较2日期对象比较它们的引用的,而不是他们的的你或许预期。

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

有几个选项,你可以存储 Date.getTime的阵列中的结果()这仅仅是一个数字再$ P $日期psentation:

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()];

然后比较一下:

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;
    }
}

演示是在这里:

这篇关于检查是否日期属于日期的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:47