簡體   English   中英

JavaScript日期對象未顯示正確的月份

[英]Javascript Date object not showing correct month

我正在嘗試使用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? 

我究竟做錯了什么?

參數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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM