我有一个接受日期和日期格式并将其转换的函数。函数的这一特定部分将日期转换为漂亮的月份格式Month abbreviation Year
。但是,getMonth()
在1月1日返回11。为什么?
调试代码:
console.log(d)
console.log(d.getMonth())
console.log(d.getMonth() + 1)
console.log(months[d.getMonth() + 1])
输出:
2017-01-01T00:00:00.000Z
11
12
undefined
修改
请参阅下面的@deceze评论。问题是时区为UTC,而我当前的时区将日期更改为12月,因此getMonth()
的时间为11。
答案 0 :(得分:0)
根据w3schools Date()
reference,您使用的是iso格式的日期,因此您必须先调用new Date("2017-01-01T00:00:00.000Z")
,然后再播放
d = new Date("2017-01-01T00:00:00.000Z");
console.log(d);
console.log(d.getMonth());
console.log(d.getMonth() + 1);