片刻JS返回不正确的值

时间:2015-02-04 21:02:49

标签: javascript node.js momentjs

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

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

enter image description here

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

enter image description here

任何人都有任何想法为什么Moment过去一个月的回复不正确?

2 个答案:

答案 0 :(得分:4)

在js个月开始时为0.所以2015, 1, 31 == 31st of February

这被解释为March, 3rd,正好落后March, 4th

一天

如果你想操纵日期 - 请使用相应的momentjs方法:http://momentjs.com/docs/#/manipulating/

答案 1 :(得分:1)

只是为了澄清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 增加1,因此它会创建3月4日而不是2月4日的日期(即月份数为2会创建3月的日期)。

3月3日至3月4日之间的差异是一天。