使用Moment.js计算直到特定日期为止的天数 [英] Calculate days to go until a particular date with momentjs

查看:103
本文介绍了使用Moment.js计算直到特定日期为止的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想倒计时直到使用momentjs进行特定事件之前的天数,但我得到了意外的结果.

I want to count down the days until a particular event using momentjs but I'm getting an unexpected result.

今天的日期是4月17日,活动的日期是5月14日,我希望得出的天数为27,但是我的代码得出的结果是57.怎么了?

With today's date being 17th April, and the event date being 14th May, I want the resulting number of days to be 27, however my code gives me a result of 57. What's wrong?

function daysRemaining() {
    var eventdate = moment([2015, 5, 14]);
    var todaysdate = moment();
    return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());

推荐答案

使用数组创建矩对象时,必须注意,月,小时,分钟,秒和毫秒都是零索引的.月份中的年和日为1的索引.这是为了反映本地 Date 参数.

When creating a moment object using an array, you have to take note that months, hours, minutes, seconds, and milliseconds are all zero indexed. Years and days of the month are 1 indexed. This is to mirror the native Date parameters.

参考

因此,可以将月份更改为4以反映5月,也可以将日期解析为 ISO 8601字符串

So either change the month to 4 to reflect May or parse the date as an ISO 8601 string

function daysRemaining() {
    var eventdate = moment("2015-05-14");
    var todaysdate = moment();
    return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());

这篇关于使用Moment.js计算直到特定日期为止的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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