Moment JS 返回不正确的值

Moment JS Returning Incorrect Value

我在使用 Moment JS NPM 时遇到一些问题。我将过去的日期设置为 1 月 31 日进行测试。它从今天的日期返回 1。看看下面我的代码和屏幕截图:

var tz = -5,
   thisYear = moment().utc(tz).year(),
// plus one because Moment starts month at 0
   thisMonth = moment().utc(tz).month() + 1,
   today = moment().utc(tz).date(),
   thisHour = moment().utc(tz).hour(),
   start = moment([2015, 1, 31, 15]),
   now = moment([thisYear, thisMonth, today, thisHour]),
   daysPast = now.diff(start, 'days');

console.log(thisYear, thisMonth, today, thisHour);
console.log(2015, 1, 31, 15);
console.log(daysPast);

这是控制台返回的内容:

当我将日期更改为二月一日时,returns 正确:

有人知道为什么 Moment 上个月返回错误吗?

在 js 中月份是从 0 开始的。所以 2015, 1, 31 == 31st of February

解释为 March, 3rd 恰好比 March, 4th

晚一天

如果您想使用日期进行操作 - 请改用相应的 momentjs 方法:http://momentjs.com/docs/#/manipulating/

只是为了澄清 zerkms 的答案,你有:

thisMonth = moment().utc(tz).month() + 1,

您正在将 thisMonth 设置为 2(如果 运行 在 2 月),那么当您这样做时:

start = moment([2015, 1, 31, 15]),

您正在创建 2 月 31 日的日期,该日期不存在,因此创建了 3 月 3 日的日期。

然后当你这样做时:

now = moment([thisYear, thisMonth, today, thisHour]),

请记住,您将 thisMonth 递增了一个,因此它创建的日期是 3 月 4 日,而不是 2 月 4 日(即月份数为 2 时创建的日期是 3 月)。

3 月 3 日和 3 月 4 日相差 1 天。