检查日期是否在11月1日到3月1日之间,如果是,那么就做点什么

时间:2012-12-20 17:23:56

标签: javascript validation date

我想在javascript中检查当前日期是在11月1日到3月之间,如果是,那么就执行某些操作。

这是我目前的代码:

var today = new Date();
if (today.getMonth() >= 10 && today.getMonth() < 2) {
    $(document).ready( function(){ 
        $.fn.test(); 
    });
}

2 个答案:

答案 0 :(得分:2)

你可以这样做:

var today = new Date();
if (today.getMonth() >= 10 || today.getMonth() < 2) {
    // ... do stuff
} 

答案 1 :(得分:0)

var d = new Date();
var MARCH_ZERO_INDEXED = 2, NOVEMBER_ZERO_INDEXED = 10;
if (MARCH_ZERO_INDEXED <= d.getMonth() && d.getMonth() < NOVEMBER_ZERO_INDEXED) {
  alert(d + " is between 1 Mar and 1 Nov");
} else {
  alert(d + " is between 1 Nov and 1 Mar of the next year");
}

var d = new Date();
var year = d.getFullYear();

var nov1 = new Date(year, 10 /* zero-indexed */, 1 /* one-indexed */);
var mar1 = new Date(year,  2, 1);

if (mar1 <= d && d < nov1) {
  alert(d + " is between 1 Mar and 1 Nov");
} else {
  alert(d + " is between 1 Nov and 1 Mar of the next year");
}

两者都假设您要使用JS解释器的时区进行测试。