JavaScript日期对象未显示正确的月份

时间:2018-10-09 10:18:56

标签: javascript

我正在尝试使用Javascript Date对象来计算将来的日期(从今天起3个月)。但是,我得到了意想不到的结果,特别是当添加3个月时,输出日期为2025(对于时间旅行者,这是今年的2018)!

做一个简单的console.log会返回一些意外的结果,如下所示:

var d = new Date();
console.log("Locale Time:"+ d.toLocaleDateString());
console.log("Month: "+d.getMonth());
d.setMonth(d.getMonth() + 3);
console.log("3 months from now: "+d.toLocaleDateString());

Returns:
// Note todays real date is 9 October 2018

Locale Time:10/9/2018 // This is correct
app.min.js:1 Month: 9 // No, the month is 10 (October)
app.min.js:1 3 months from now: 11/9/2025 // What? 

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

参数monthIndex基于0。这意味着一月= 0,十二月= 11。 因此您的代码可以像这样:

var d = new Date();
console.log("Locale Time:"+ d.toLocaleDateString());
console.log("Month: "+d.getMonth());
d.setMonth(d.getMonth() + 4);
console.log("3 months from now: "+d.toLocaleDateString());

输出将为

> "Locale Time:10/9/2018"
> "Month: 9" (October = 9 as monthIndex starts from 0)
> "3 months from now: 2/9/2019"
相关问题