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.

这里已经说明了,setMonth的时候会把当前的date应用到目标的month, 如果date超出目标月份的日期,可能就会到下个月了。举个例子

当前是2023-03-30

如果new Date()  之后setMonth(date.getMonth() - 1) 也就是上个月,实际上结果会变成 2023-03-02, 因为set完之后变成2023-02-30, 实际2月28天就到了03-02

let date = new Date();

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。