我试图使用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日)作为过去的日期。

知道我哪里做错了吗?


当前回答

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

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>

其他回答

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

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>

// Returns true if it is today or false if it's not
moment(SpecialToDate).isSame(moment(), 'day');

你可以使用isSame函数:

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

}

invert is before方法检查日期是否与今天或未来相同,如下所示:

!moment(yourDate).isBefore(moment(), "day");