我试图使用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日)作为过去的日期。
知道我哪里做错了吗?
在阅读文档:http://momentjs.com/docs/#/displaying/difference/之后,您必须将diff函数视为减号运算符。
// today < future (31/01/2014)
today.diff(future) // today - future < 0
future.diff(today) // future - today > 0
因此,你必须扭转你的状况。
如果你想检查是否一切正常,你可以在函数中添加一个额外的参数:
moment().diff(SpecialTo, 'days') // -8 (days)
我想用它做别的事情,但最终发现了一个你可以尝试的技巧
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>