首先获取最近几周 例如获取最近三周
/**获取周 */
getBeforeWeeksTime(num) {
/**获取到当前的年月日 */
var now = new Date();
var year = now.getFullYear(); //年
var month = now.getMonth() + 1; //月
var day = now.getDate(); //日
let currentYear = year.toString();
let currentMonth = ''
if (month < 10)
currentMonth += "0";
currentMonth += month
let currentDay = ''
if (day < 10)
currentDay += "0";
currentDay += day;
var nowDate = new Date(year, parseInt(month) - 1, day); //获取到今天的时间
var startDate = new Date(year, 0, 1); //获取到今年第一月第一天
let d = Math.round((nowDate.valueOf() - startDate.valueOf()) / 86400000); // d是当前日期是今年第多少天
//用d + 当前年的第一天的周差距的和在除以7就是本年第几周
let currentWeek = year + '-' + (Math.ceil((d + (startDate.getDay() + 1 - 1)) / 7) + 1 - num) //获取到最近num周是第几周
console.log('currentWeek', currentWeek);
let weekNo = currentWeek.split("-")[1]; //获取想要计算的周是一年的第多少周
let oneday = new Date(year + "-01-01").getDay();// 此年1号是星期几
// 方便计算,当为星期天时为7
if (oneday == 0) {
oneday = 7;
}
let one_fistday;
let one_lastday;
// 如果1号刚好是星期一
if (oneday == 1) {
one_fistday = year + "-01-01";
one_lastday = year + "-01-07";
} else {
let jj = 8 - oneday;
one_fistday = year - 1 + "-12-" + (31 - oneday + 2 > 9 ? 31 - oneday + 2 : "0" + (31 - oneday + 2));
one_lastday = year + "-01-" + (jj > 9 ? jj : "0" + jj);
}
let fistday;
let lastday;
// 如果刚好是第一周
if (weekNo == 1) {
fistday = one_fistday;
lastday = one_lastday;
} else {
fistday = this.addDate(one_lastday, (weekNo - 2) * 7 + 1);
lastday = this.addDate(one_lastday, (weekNo - 1) * 7);
}
let obj = {
beforeMonday: fistday,
beforeSunday: lastday,
}
return obj;
/**
* fistday 为前第几周的周一 格式(xxxx-xx-xx)
* lastday 为前第几周的周日 格式(xxxx-xx-xx)
*/
},
addDate(date, days) {
var d = new Date(date);
d.setDate(d.getDate() + days);
var m = d.getMonth() + 1;
return (
d.getFullYear() +
"-" +
(m > 9 ? m : "0" + m) +
"-" +
(d.getDate() > 9 ? d.getDate() : "0" + d.getDate())
);
},
获取本周的最后一天 :
/**获取本周最后一天 */
getLastWeek() {
let lastTime = new Date(new Date().getTime() + 3600 * 1000 * 24 * (7 - new Date().getDay()));
let date = new Date(lastTime)
let y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? '0' + m : m
let d = date.getDate()
d = d < 10 ? '0' + d : d
let resTime = y + '-' + m + '-' + d
return resTime
},