获取一周的时间数组(周一到周天)
2020-01-08 本文已影响0人
可爱的木头
judgeIsLeap(year) {
//闰年条件 能被4整除不能被100整除、或者能被400整除
return year % 100 == 0 ? (year % 400 == 0 ? 1 : 0) : year % 4 == 0 ? 1 : 0;
}
getWeekArray(timestamp) {
const time = new Date(timestamp);
const year = time.getFullYear();
const month = time.getMonth();
const day = time.getDate();
const week = time.getDay() === 0 ? 7 : time.getDay();
const monthDays = [31, 28 + this.judgeIsLeap(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let dayArray = Array(7).fill(0);
dayArray[week - 1] = new Date(timestamp).getTime();
dayArray.map((item, index) => {
if (!item) {
const countDays = monthDays[month];
let currentMonth = month;
let currentYear = year;
let t = day - week + index + 1;
if (t <= 0) {
currentMonth = month - 1;
if (currentMonth < 0) {
currentMonth = 11;
currentYear = currentYear - 1;
}
t = monthDays[currentMonth] + t;
}
if (t > countDays) {
currentMonth = month + 1;
if (currentMonth > 11) {
currentMonth = 0;
currentYear = currentYear + 1;
}
t = t - monthDays[currentMonth];
}
dayArray[index] = dayjs(timestamp)
.set('year', currentYear)
.set('month', currentMonth)
.set('date', t)
.valueOf();
}
});
return dayArray;
}