setMonth方法关于月底的坑
早上一来被测试提了个bug,时间选择器本来默认都是显示上个月时间的,今天变成了显示本月的时间。
我获取上个月月份的方法如下:
// 比如今天是 2024-05-34 号,前一个月应该是 2024-04-30
let lastMonth = new Date(new Date("2024-05-31").setMonth(new Date("2024-05-31").getMonth() - 1))
console.log('lastMonth :', lastMonth .toLocaleString())
// now : 2024/05/01 上午8:00:00
原来对于setMonth这个方法,在使用的时候是可能会出现问题的。
分析
T.setMonth(M)方法,计算时间T的日期在M月上的映射,即以M月的月长为跨度计算。
1. 在获取上一个月时,如果T为5月31号,M为4月,即希望获取4月的31号,而4月没有31号,就会累加,得到的日期为5月1号。
2. 同理获取下一个月,如果T为5月31号,M为6月,即希望获取6月的31号,而6月没有31号,就会累加,得到的日期为7月1号。
3. 对于特殊月份2月更是,如果T为3月31号,M为2月,即希望获取2月的31号,而2月没有31号,就会累加,得到的日期为3月2号。
let lastMonth = new Date(new Date("2024-05-31").setMonth(new Date("2024-05-31").getMonth() - 1))
console.log('lastMonth:', lastMonth.toLocaleString())
// lastMonth: 2024/05/01 上午8:00:00
let nextMonth = new Date(new Date("2024-05-31").setMonth(new Date("2024-05-31").getMonth() + 1))
console.log('nextMonth :', nextMonth.toLocaleString())
// nextMonth: 2024/07/01 上午8:00:00
解决
1. 减去当前月份的天数
用当前时间 - 当前月份的天数,即可得到上个月
用当前时间 + 下个月份的天数,即可得到下个月
// 减去当前月份的月长:24 * 60 * 60 * 1000 * new Date('2024-03-31').getDate()
let lastMonth = new Date(new Date('2024-05-31').getTime() - 24 * 60 * 60 * 1000 * new Date('2024-05-31').getDate())
console.log('lastMonth :', lastMonth.toLocaleString())
// lastMonth : 2024/04/30 上午8:00:00
2. setDate(1)
setMonth 之前先 setDate(1),将当前日期变为1号
const now = new Date('2024-03-15')
now.setDate(1)
now.setMonth(now.getMonth() - 1)
console.log(now.toLocaleString())
// 2024/2/1 08:00:00