js获取某一个时间的上周或者上月的起终点

本文介绍了一种使用JavaScript来确定当前日期的前一周和前一个月的起始与结束日期的方法。通过计算日期偏移量,可以精确地获取到上一周的第一天和最后一天,以及上个月的第一天和最后一天,适用于各种需要日期区间计算的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js获取某一个时间的上周或者上月的起终点

上周

function getSomeTimesWeekDate(Time = new Date()) {
			let weekNum = Time.getDay();	//获取当前是周几
			weekNum = weekNum == 0 ? 7 : weekNum;
			let lastDate = new Date(Time.getTime() - weekNum * 24 * 60 * 60 * 1000);
			let fitstDate = new Date(Time.getTime() - ((weekNum + 6) * 24 * 60 * 60 * 1000));
			let startDate =
				`${fitstDate.getFullYear()}-${fitstDate.getMonth()+1<10?'0'+(fitstDate.getMonth()+1):fitstDate.getMonth()+1}-${fitstDate.getDate()<10?'0'+fitstDate.getDate():fitstDate.getDate()} 00:00:00`
			let endDate =
				`${lastDate.getFullYear()}-${lastDate.getMonth()+1<10?'0'+(lastDate.getMonth()+1):lastDate.getMonth()+1}-${lastDate.getDate()<10?'0'+lastDate.getDate():lastDate.getDate()} 23:59:59`
			return [startDate, endDate]
		}

上个月

function getSomeTimesMonthDate(Time = new Date()) {
			let year = Time.getFullYear();
			let month = Time.getMonth();
			if (month == 0) {
				month = 12;
				year = year - 1;
			}
			if (month < 10) {
				month = '0' + month;
			}
			let myDate = new Date(year, month, 0); //上个月的最后一天的开始
			let startDate = `${year}-${month}-01 00:00:00`;
			let endDate = `${year}-${month}-${myDate.getDate()} 23:59:59` 
			return [startDate, endDate]
		}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乔的大明

您的鼓励,我会库库更更。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值