moment.js中的diff比较操作

时间:2017-11-14 09:57:31

标签: javascript jquery html momentjs

这是this问题的重复。我不知道如何比较差异。例如,如果diff等于大于14天,则文本框应为红色。如果7到13天它将是黄色,而在6天以下它将是绿色。

代码:

function compare() {
 var firstDate = moment($("#date1").val(), "MM-DD-YYYY");
  var secondDate = moment($("#date2").val(), "MM-DD-YYYY");

  console.log(firstDate.inspect(), secondDate.inspect());

  if (firstDate.isValid() && secondDate.isValid()) {
    // you need a validation before using diff function of momentjs
    var diff = Math.abs(firstDate.diff(secondDate, 'days'));
    console.log(diff);
    // you also need to remove all classes before adding new class
    $("#status").removeClass("redBg").removeClass("greenBg").removeClass("yellowBg");
    if (diff => 14) {
      $("#status").addClass('redBg');
    } else if (7 < diff =< 9) {
      $("#status").addClass('greenBg');
    } else if(diff >= 6) {
      $("#status").addClass('yellowBg');
    }
  } else {
    $("#status").addClass('yellowBg');
  }
    
    });
.greenBg {
    background: green;
}

.yellowBg {
    background: yellow;
}

.redBg {
    background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<html>
<body>
    <input type="text" id="date1" onchange=/>
<input type="text" id="date2" onchange='compare()'/>
<input  readonly type="text" id="status"/>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

这不是有效条件:else if(7 < diff =< 9),它应该是else if(diff > 7 && diff <= 9)