仅做记录 代码写的一般 如有错误或更好的写法 请指出 谢谢
需求:选择年份,获取当前年份的所有周数,如果最后一周不满七天 只返回当前年的日期
期望数据格式 :
[
{start:'01-01',end:'01-07'},
{start:'01-08',end:'01-14'},
{start:'01-15',end:'01-21'}......
]
代码实现
calculateWeekNumber(year) {
if (!year) {
return "请输入年份";
}
const startDate = new Date(year, 0, 1); // 获取该年1月1日
const endDate = new Date(year, 11, 31); // 获取该年12月31日
let weekData = [];
while (startDate <= endDate) {
const start = new Date(
startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()
)
.toISOString()
.slice(0, 10); // 获取该日的开始日期
const end = new Date(
startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate() + 6
)
.toISOString()
.slice(0, 10); // 获取该日的结束日期
weekData.push({ start, end }); // 添加到周数据数组中
startDate.setDate(startDate.getDate() + 7); // 更新到下一个星期
}
//如果最后一周不满7天,只返回当前年的日期
if (
weekData[weekData.length - 1].end !== endDate.toISOString().slice(0, 10)
) {
weekData[weekData.length - 1].end = endDate.toISOString().slice(0, 10);
}
weekData = weekData.map((item, index) => {
return { ...item, week: index + 1 };
});
return weekData
},