function getWeekStartAndEnd() {
const oneDayTime = 1000 * 60 * 60 * 24; // 一天里一共的毫秒数
const today = new Date();
const todayDay = today.getDay(); // 获取今天是星期几,假设是周3
const startDate = new Date(
today.getTime() - oneDayTime * (todayDay - 1)
);
const endDate = new Date(today.getTime() + oneDayTime * (7 - todayDay));
return { startDate, endDate };
}
const week = getWeekStartAndEnd();
console.log(week.startDate, week.endDate);
但是当今天是周日的时候today是0
改善一下
function getWeekStartAndEnd(timestamp) {
const oneDayTime = 1000 * 60 * 60 * 24; // 一天里一共的毫秒数
const today = timestamp ? new Date(timestamp) : new Date();
const todayDay = today.getDay() || 7; // 若那一天是周末时,则强制赋值为7
const startDate = new Date(
today.getTime() - oneDayTime * (todayDay - 1)
);
const endDate = new Date(today.getTime() + oneDayTime * (7 - todayDay));
return { startDate, endDate };
}