需求描述:
需要做一个表格,表格的X轴是当前月份中每周周日的日期,Y轴是每周的数据总和。
以下是获取X轴数据的方法。
初级版:
week = () => {
let zhou = 0;
let currentDate = new Date();
let year = currentDate.getFullYear();
let month = currentDate.getMonth() + 1;
let customTime = year + `/` + month + `/` + `01`;
let startDate = new Date(customTime)
// 获取当月1号是周几
let day = parseInt(startDate.getDay()) == 0 ? 7 : parseInt(startDate.getDay());
// 获取当月的总天数
let days = new Date(year, month, 0).getDate();
// 一周有7天,获取不足一周的有几天
let y = days % 7;
// 判断当月有几周
if (7 - day >= y) {
zhou = parseInt(days / 7) + 1;
} else {
zhou = parseInt(days / 7) + 2;
}
// 获取月末是周几
let endDate = new Date(year + `/` + month + `/` + days).getDay();
// 如果月末是周日,则当月的周数-1
if (endDate == 0) {
zhou = zhou - 1;
}
console.log(month + '月有' + zhou + '周')
let timesArray = [];
timesArray[0] = 1 + (7 - day);
for (let i = 1; i < zhou; i++) {
if (i == 1) {
timesArray[i] = timesArray[0] + 7;
} else {
timesArray[i] = timesArray[i - 1] + 7;
}
}
// 如果最后一周的日期大于当月总天数(如:月末是30号,最后一周是35号),则删除最后一周的数据。
if (timesArray[zhou - 1] > days) {
timesArray = timesArray.splice(0, zhou - 1)
}
// 进行数据格式化
var array = timesArray.map(function (item) {
return year + '-' + month + `-` + item;
});
console.log('分别是', array)
}
week();
进阶版:
进阶版的方法,可以通过传入参数,灵活获取每周中任意一天是几号。
/**
* @param {timeStamp/string} date 非必传。例如:传入'2021-01-01',则查找2021年1月份,默认查找当前月份。
* @param {number} expectDay 非必传。例如:传入3,则查找当前月份中每周三是几号,其中(0代表周日, 1-6分别代表周一至周六),默认0。
*/
function weeks(expectDay, date) {
//fix arugments
if (typeof date == "string") {
date = new Date(date);
} else if (typeof date == "number") {
date = new Date(date);
} else if (date == null) {
date = new Date();
} else if (!(date instanceof Date)) {
throw "unexpect type of date";
}
expectDay = expectDay % 7;
if (!expectDay) {
expectDay = 0;
}
// find first expect day
date.setDate(1);
if (date.getDay() != expectDay) {
date.setDate((expectDay + 7 - date.getDay()) % 7 + 1);
}
// record current month
var month = date.getMonth();
var arr = [];
do {
// push expect days
arr.push(date.toISOString().substring(0, 10));
date.setDate(date.getDate() + 7);
// keep month
} while (date.getMonth() == month);
return arr;
}
console.log('分别是', weeks());
更新日期:2021年11月12日
感谢@阿七月指出的bug