检查所选日期值是否比今天的日期大至少一个月

时间:2019-06-01 16:20:52

标签: javascript

我正在尝试编写一个函数,以检查从输入类型month标记中选择的日期是否比当前日期大至少一个月。但是当我比较这些值时,我的函数不起作用,因为它比较的是错误的数字。这是我尝试过的:

    function validateDate(date) {
    var date = new Date(date);
    var now = new Date();
    now.setHours(0,0,0,0);
    alert(date);

    if(date.getFullYear() < now.getFullYear()){
        alert("date selected is less than todays year")
        return false;
    }
    else{
        if(date.getFullYear() === now.getFullYear()){
            var nowMonth = now.getMonth();
            var dateMonth = date.getMonth();

            if(dateMonth <= nowMonth){
                alert("date selected is less than or equal to todays"+ nowMonth + dateMonth)
                return false;
            }
            else{
                return true;
            }
        }else{
            return true;
        }
    }}

这是我的日期选择器:

但是问题是,当我使用它来获取日期时:

        var nowMonth = now.getMonth();
        var dateMonth = date.getMonth();
January == 11
February == 0
March == 1
April == 2
etc...

我该如何解决?

1 个答案:

答案 0 :(得分:0)

我已经在jsfiddle上尝试过它,但它不喜欢的是ist您选择的变量名

    function validateDate(dateselect) {
  var datenew = new Date(dateselect);
  var nowdate = new Date();
  nowdate.setHours(0, 0, 0, 0);

  if (datenew.getFullYear() < nowdate.getFullYear()) {
    alert("date selected is less than todays year")
    return false;
  } else {
    if (datenew.getFullYear() === nowdate.getFullYear()) {
      var nowMonth = nowdate.getMonth();
      var dateMonth = datenew.getMonth();
alert(nowMonth + ' ' + dateMonth);

      if (dateMonth <= nowMonth) {
        alert("date selected is less than or equal to todays" + nowMonth + dateMonth)
        return false;
      } else {
        return true;
      }
    } else {
      return true;
    }
  }
}

现在显示5和5 尝试一下 https://jsfiddle.net/5zwktasn/