我在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);


这是在控制台中返回的内容:



当我将日期更改为2月1日时,它会正确返回:

 

任何人都知道为什么Moment在过去的一个月中错误地返回了吗?

最佳答案

只是为了澄清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日之间的区别是一天。

09-25 17:22
查看更多