js根据年月获取这个月的所有周
额这是俺第一次写博客有点小激动,写了一个小功能,有问题请指导,没有注释不要怼俺。
/**
* @package year 年
* @package month 月
* @return Object key值是当前第几周 value值是当前一周的7天的日期
*/
function getWeek(year, month) {
year = year || (new Date()).getFullYear();
month = month || (new Date()).getMonth();
let fnToDub = time => time < 10 ? ('0' + time) : +time,
fnGenerateDate = (time, end) => {
let j = +time, array = [], i = 0;
for (; j <= +end; j++) {
array.push(j)
}
if (array.length < 7) {
for (; array.length < 7; i++) {
array.push(i + 1);
}
}
return array;
};
const d = new Date();
d.setFullYear(year, month - 1, 1);
let w1 = d.getDay() === 0 ? 7 : d.getDay();
d.setFullYear(year, month, 0);
const dd = d.getDate();
const d1 = w1 !== 1 ? 7 - w1 + 2 : 1;
const week_count = Math.ceil((dd - d1 + 1) / 7);
let allWeek = {}, i = 0;
for (; i < week_count; i++) {
const sunday = fnToDub((d1 + i * 7) + 6);
const start = year + '' + fnToDub(month) + '' + fnToDub(d1 + i * 7);
const end = sunday <= dd ? year + '' + fnToDub(month) + '' + sunday : d.getFullYear() + '' + (d.getMonth() + 1) + '' + fnToDub(d.getDate());
if (sunday > dd) d.setFullYear(year, fnToDub(month) - 1, sunday);
allWeek[(i + 1)] = {
start: start,
end: end
}
}
function g() {
const num1 = new Date(year, month - 1, 0).getDate(),
day = +allWeek[1].start.slice(-2) - 1;
let ary = [], i = 1, j = 0;
for (; i <= (7 - day); i++) {
ary.unshift(num1 - i + 1);
}
for (; j < day; j++) {
ary.push(j + 1)
}
return day > 0 ? ary : false;
}
if (g()) allWeek[0] = g();
let obj = {}, dayType1 = +allWeek[1].start.slice(-2) === 1;
for (let k in allWeek) {
obj[dayType1 ? k : +k + 1] = allWeek[k].length ? allWeek[k] : fnGenerateDate(allWeek[k].start.slice(-2), allWeek[k].end.slice(-2));
}
return obj
}
console.log(getWeek(2019, 12));