获取当前天所在周的开始结束时间

231 阅读1分钟

移动端APP中有周报需求,需要获取当前周的开始时间和结束时间,并且用户可以按周选择当前周一年内的周报日期(比如今天2020-08-28;选择周的时间段从2019-08-28所在周到2020-08-28所在周,一年内的所有周)。

代码如下:

let weeksTotal = [];
for(let i = 0; i < 53; i++) {
					let today = new Date();
					let  oToday  =  new  Date(today.getTime()  -  i * 7  *  24  *  3600  *  1000);
					let currentDay = oToday.getDay();
					if(currentDay == 0) {
						currentDay = 7
					}
					let mondayTime = oToday.getTime() - (currentDay - 1) * 24 * 60 * 60 * 1000;
					let sundayTime = oToday.getTime() + (7 - currentDay) * 24 * 60 * 60 * 1000;
					weeksTotal.push({
						start: new Date(mondayTime).toLocaleDateString(),
						end: new Date(sundayTime).toLocaleDateString(),
						name: new Date(mondayTime).toLocaleDateString() + '-' + new Date(sundayTime).toLocaleDateString(),
					})
				}