首页 |  我的博客 |  查看该博主内容分类 | 

javascript如何获取当前日期的上个月最后一天的日期?

思路

Date实例化时指定date为0即可获得上个月最后一天的Date实例

示例

lastMonthLastDate(){
	const nowDate = new Date()
	let nowYear = nowDate.getFullYear()
	let nowMonth = (nowDate.getMonth() + 1).toString().padStart(2, '0')
	let lastDate = new Date(nowYear, nowMonth - 1, 0)   // 关键代码
	let lastYear = lastDate.getFullYear()
	let lastMonth = (lastDate.getMonth() + 1).toString().padStart(2, '0')
	let lastDay = lastDate.getDate().toString().padStart(2, '0')
	
	return `${lastYear}-${lastMonth}-${lastDay}`
}
nowLastMonthDate = lastMonthLastDate()
console.log('nowLastMonthDate', nowLastMonthDate)
posted @ 2024-02-07 15:37  Z哎呀  阅读(35)  评论(0)    收藏  举报