Moment JS-检查日期是今天还是将来 [英] Moment JS - check if a date is today or in the future

查看:1658
本文介绍了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)

这篇关于Moment JS-检查日期是今天还是将来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆