今天检查是否在日期数组

时间:2017-06-21 09:04:34

标签: javascript date

我试图检查今天(0:00)是否在日期数组中,如下所示:



var today = new Date();
today.setHours(0, 0, 0, 0);
var holidays = [
  new Date(2017, 5, 21, 0, 0, 0).getTime(), // Today
  new Date(2017, 5, 22, 0, 0, 0).getTime(),
  new Date(2017, 5, 23, 0, 0, 0).getTime(),
  new Date(2017, 5, 24, 0, 0, 0).getTime(),
  new Date(2017, 5, 25, 0, 0, 0).getTime()
];
if ($.inArray(today, holidays) > -1) {
  alert('Closed');
} else {
  alert('Open');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

但正如你所看到的,它今天没有找到(6月21日),

知道我错过了什么吗?

3 个答案:

答案 0 :(得分:5)

您正在将日期对象与时间进行比较:

var today = new Date();
today.setHours(0, 0, 0, 0);
var holidays = [
  new Date(2017, 5, 21, 0, 0, 0).getTime(), // Today
  new Date(2017, 5, 22, 0, 0, 0).getTime(),
  new Date(2017, 5, 23, 0, 0, 0).getTime(),
  new Date(2017, 5, 24, 0, 0, 0).getTime(),
  new Date(2017, 5, 25, 0, 0, 0).getTime()
];
if ($.inArray(today.getTime(), holidays) > -1) {
  alert('Closed');
} else {
  alert('Opened');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:2)

在您的$ .inArray电话中,今天更改&#34;&#34; to&#34; today.getTime()&#34;

答案 2 :(得分:0)

todaytoday.getTime()不同。

&#13;
&#13;
var today = new Date();
today.setHours(0, 0, 0, 0);
today=today.getTime();
var holidays = [
  new Date(2017, 5, 21, 0, 0, 0).getTime(), // Today
  new Date(2017, 5, 22, 0, 0, 0).getTime(),
  new Date(2017, 5, 23, 0, 0, 0).getTime(),
  new Date(2017, 5, 24, 0, 0, 0).getTime(),
  new Date(2017, 5, 25, 0, 0, 0).getTime()
];
if ($.inArray(today, holidays) > -1) {
  alert('Closed');
} else {
  alert('Opened');
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;