moment.js中的差异比较操作 [英] diff comparison operation in moment.js
本文介绍了moment.js中的差异比较操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是此的重复项一个>问题.我不知道如何比较差异.例如,如果差异大于14天,则文本框应为红色.如果7到13天为黄色,低于6天则为绿色.
This is Duplicate of this question. I don't know how to compare the diff. For example if the diff equal to greater than 14 days then the text box should be red. if 7 to 13 days it would be yellow and below 6 days it would be green.
代码:
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>
推荐答案
这不是有效条件:else if(7 < diff =< 9)
,应该为else if(diff > 7 && diff <= 9)
This is not a valid condition: else if(7 < diff =< 9)
, it shoud be else if(diff > 7 && diff <= 9)
这篇关于moment.js中的差异比较操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文