Moment JS-检查日期是今天还是将来

问题描述:

我正在尝试使用momentjs检查给定的日期是今天还是将来.

I am trying to use momentjs to check if a given date is today or in the future.

这是我到目前为止所拥有的:

This is what I have so far:

<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日)评估为过去的日期.

The code is evaluating my date (31st of Jan 2014) as a date in past.

知道我在做什么错吗?

阅读文档后: http://momentjs.com/docs/#/displaying/difference/,您必须将diff函数视为减号运算符.

After reading the documentation: http://momentjs.com/docs/#/displaying/difference/, you have to consider the diff function like a minus operator.

                   // today < future (31/01/2014)
today.diff(future) // today - future < 0
future.diff(today) // future - today > 0

因此,您必须逆转您的情况.

Therefore, you have to reverse your condition.

如果要检查一切都可以,可以向该函数添加一个额外的参数:

If you want to check that all is fine, you can add an extra parameter to the function:

moment().diff(SpecialTo, 'days') // -8 (days)