JS date setMonth 的問題

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth

來看MDN的說明

The current day of month will have an impact on the behavior of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.

這里已經(jīng)說明了,setMonth的時候會把當(dāng)前的date應(yīng)用到目標(biāo)的month, 如果date超出目標(biāo)月份的日期,可能就會到下個月了。舉個例子

當(dāng)前是2023-03-30

如果new Date()? 之后setMonth(date.getMonth() - 1) 也就是上個月,實際上結(jié)果會變成 2023-03-02, 因為set完之后變成2023-02-30, 實際2月28天就到了03-02

let date = new Date();

date.setMonth(date.getMonth() - 1)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容