獲取月份的自然周
阿新 • • 發佈:2022-12-12
//獲取當前月有幾周 getWeeks(year, month) { var d = new Date(); // 該月第一天 d.setFullYear(year, month - 1, 1); var w1 = d.getDay(); if (w1 == 0) w1 = 7; // 該月天數 d.setFullYear(year, month, 0); var dd = d.getDate(); // 第一個週一 let d1; if (w1 != 1) d1 = 7 - w1 + 2;else d1 = 1; let week_count = Math.ceil((dd - d1 + 1) / 7); return week_count; }, //根據年月周獲取該周從週一到週日的日期 getWeekTime(year, month, weekday, timeArr) { var d = new Date(); // 該月第一天 d.setFullYear(year, month - 1, 1); var w1 = d.getDay(); if (w1 == 0) w1 = 7;// 該月天數 d.setFullYear(year, month, 0); var dd = d.getDate(); // 第一個週一 let d1; if (w1 != 1) d1 = 7 - w1 + 2; else d1 = 1; var monday = d1 + (weekday - 1) * 7; var sunday = monday + 6; var from = year + "-" + month + "-" + monday; var to; if(sunday <= dd) { to = year + "-" + month + "-" + sunday; } else { d.setFullYear(year, month - 1, sunday); let days = d.getDate(); to = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + days; } if (timeArr) { return from + '~' + to } return '第' + weekday + '周:' + from + '~' + to } var weekNUm =_t.getWeeks(2022, 12); for (var k = 1; k <= weekNUm; k++) { _t.getWeekTime(todayYear, todayMonent, k); }