[英]Moment JS Returning Incorrect Value
I am having some issues with the Moment JS NPM. 我在Moment JS NPM上遇到一些问题。 I have a date in the past set to Jan 31st for testing.
我将过去的日期定为1月31日进行测试。 It is returning as 1 from today's date.
从今天开始,它以1返回。 Take a look at my code and screenshots below:
在下面查看我的代码和屏幕截图:
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);
This is what is getting returned in the console: 这是在控制台中返回的内容:
When I change the date to the first of February, it returns correctly: 当我将日期更改为2月1日时,它会正确返回:
Anyone have any ideas why Moment is returning incorrectly with the past month? 任何人都知道为什么Moment在过去的一个月中无法正确返回?
In js months start with 0. So 2015, 1, 31
== 31st of February
在js月份中,数字从0开始。因此,
2015, 1, 31
== 31st of February
Which is interpreted as March, 3rd
which is exactly one day behind March, 4th
解释为
March, 3rd
恰好是March, 4th
日之后的一天
If you want to manipulate with dates - use the corresponding momentjs methods instead: http://momentjs.com/docs/#/manipulating/ 如果要处理日期,请改用相应的momentjs方法: http ://momentjs.com/docs/#/manipulating/
Just to clarify zerkms answer, where you have: 只是为了澄清zerkms的答案,您在哪里:
thisMonth = moment().utc(tz).month() + 1,
you are setting thisMonth to 2 (if run in Feburary), then when you do: 您将thisMonth设置为2(如果在2月运行),则在执行以下操作时:
start = moment([2015, 1, 31, 15]),
you are creating a date for 31 February, which doesn't exist so a date for 3 March is created. 您正在创建2月31日的日期,该日期不存在,因此创建了3月3日的日期。
Then when you do: 然后,当您这样做时:
now = moment([thisYear, thisMonth, today, thisHour]),
remember that you incremented thisMonth by one, so it creates a date for 4 March, not 4 February (ie a month number of 2 creates a date for March). 请记住,您将thisMonth递增了一个,因此它创建的日期是3月4日,而不是2月4日(例如,月份数2创建的是3月的日期)。
The difference between 3 March and 4 March is one day. 3月3日和3月4日之间的区别是一天。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.