js 獲取年度自然周
阿新 • • 發佈:2021-06-16
- 本文作者:bigroc
- 本文連結:https://www.cnblogs.com/bigroc/p/14888550.html
js程式碼
function getWeeks() { // 當年的年份 let year = new Date().getFullYear(); let data = [] let d = new Date(year, 0, 1); while (d.getDay() !== 1) { // 以第一個星期一為開始日期 d.setDate(d.getDate() + 1); } let to = new Date(year, 11, 31); while (to.getDay() !== 0) { // 以星期日為結束日期 to.setDate(to.getDate() + 1); } let i = 1; for (let from = d; from < to;) { // 可按照要求重構下面程式碼 let str = ''; str = str + (i < 10 ? '0' + i : i) + "(周)" + year + "-" + ((from.getMonth() + 1) <= 9 ? ('0' + (from.getMonth() + 1)) : (from.getMonth() + 1)) + "-" + (from.getDate() <= 9 ? ('0' + from.getDate()) : from.getDate()) + " 至 "; from.setDate(from.getDate() + 6); if (from < to) { str = str + year + "-" + ((from.getMonth() + 1) <= 9 ? ('0' + (from.getMonth() + 1)) : (from.getMonth() + 1)) + "-" + (from.getDate() <= 9 ? ('0' + from.getDate()) : from.getDate()); from.setDate(from.getDate() + 1); } else { str = str + year + "-" + ((to.getMonth() + 1) <= 9 ? ('0' + (to.getMonth() + 1)) : (to.getMonth() + 1)) + "-" + (to.getDate() <= 9 ? ('0' + to.getDate()) : to.getDate()); } let obj = { sun: i, week: year + "-" + str.split("(周)")[0], weekName: year + "-" + str.split("(周)")[0] + "(周)", startDate: str.split("(周)")[1].split(" 至 ")[0], entData: str.split("(周)")[1].split(" 至 ")[1] } data.push(obj) i++; } return data; }