我试图使用momentjs来检查给定的日期是今天还是将来。

这是我目前所拥有的:

<script type="text/javascript" src="http://momentjs.com/downloads/moment.min.js"></script>
<script type="text/javascript">

var SpecialToDate = '31/01/2014'; // DD/MM/YYYY

var SpecialTo = moment(SpecialToDate, "DD/MM/YYYY");
if (moment().diff(SpecialTo) > 0) {
    alert('date is today or in future');
} else {
    alert('date is in the past');
}

</script>

代码评估我的日期(2014年1月31日)作为过去的日期。

知道我哪里做错了吗?


当前回答

最简单的答案是:

const firstDate = moment('2020/10/14'); // the date to be checked
const secondDate = moment('2020/10/15'); // the date to be checked

firstDate.startOf('day').diff(secondDate.startOf('day'), 'days'); // result = -1
secondDate.startOf('day').diff(firstDate.startOf('day'), 'days'); // result = 1

它将检查midnight值并返回准确的结果。当两个日期之间的时间差小于24小时时,它也会工作。

其他回答

你可以使用isSame函数:

var iscurrentDate = startTime.isSame(new Date(), "day");
if(iscurrentDate) {

}

用最简单的一个来检查未来的日期

if(moment().diff(yourDate) >=  0)
     alert ("Past or current date");
else
     alert("It is a future date");

我想用它做别的事情,但最终发现了一个你可以尝试的技巧

somedate。calendar(compareDate, {sameDay: '[Today]'})=='今天'

var d = moment(); var today = moment(); console.log("Usign today's date, is Date is Today? ",d.calendar(today, { sameDay: '[Today]'})=='Today'); var someRondomDate = moment("2012/07/13","YYYY/MM/DD"); console.log("Usign Some Random Date, is Today ?",someRondomDate.calendar(today, { sameDay: '[Today]'})=='Today'); var anotherRandomDate = moment("2012/07/13","YYYY/MM/DD"); console.log("Two Random Date are same date ? ",someRondomDate.calendar(anotherRandomDate, { sameDay: '[Today]'})=='Today'); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

你可以使用momentjs的isAfter()查询函数:

检查一个时刻是否在另一个时刻之后。

moment('2010-10-20').isAfter('2010-10-19'); // true

如果希望将粒度限制为毫秒以外的单位,请将单位作为第二个参数传递。

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false

moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

http://momentjs.com/docs/#/query/is-after/

选择yesterday,在moment()的帮助下检查过去的天数。减去(1天);

Reference:- http://momentjs.com/docs/#/manipulating/subtract/ function myFunction() { var yesterday = moment().subtract(1, "day").format("YYYY-MM-DD"); var SpecialToDate = document.getElementById("theDate").value; if (moment(SpecialToDate, "YYYY-MM-DD", true).isAfter(yesterday)) { alert("date is today or in future"); console.log("date is today or in future"); } else { alert("date is in the past"); console.log("date is in the past"); } } <script src="http://momentjs.com/downloads/moment.js"></script> <input type="date" id="theDate" onchange="myFunction()">