// 获取当前日期 const d = new Date(); const currentYear = d.getFullYear(); const currentMonth = d.getMonth();
// 计算当前月的周数 function getWeeksInMonth(year, month) { const weeks = []; const firstDay = new Date(year, month, 1); const lastDay = new Date(year, month + 1, 0);
let currentWeekStart = new Date(firstDay);
// 调整到周一开始(如果第一天不是周一)
if (currentWeekStart.getDay() !== 1) {
const dayOffset = currentWeekStart.getDay() === 0 ? -6 : 1 - currentWeekStart.getDay();
currentWeekStart.setDate(currentWeekStart.getDate() + dayOffset);
}
// 重置周计数器
let weekCounter = 1;
while (currentWeekStart <= lastDay) {
const weekEnd = new Date(currentWeekStart);
weekEnd.setDate(weekEnd.getDate() + 6);
// 确保周结束日期不超过当月最后一天
if (weekEnd > lastDay) {
weekEnd.setTime(lastDay.getTime());
}
// 只有当这一周包含当前月的日期时才添加
if (weekEnd.getMonth() === month || currentWeekStart.getMonth() === month) {
// 获取本周的周六和周日日期
const saturday = new Date(currentWeekStart);
saturday.setDate(currentWeekStart.getDate() + 5); // 周六是开始日期+5天
const sunday = new Date(currentWeekStart);
sunday.setDate(currentWeekStart.getDate() + 6); // 周日是开始日期+6天
// 格式化日期为 MM月DD日
const formatDate = (date) => {
return `${date.getMonth() + 1}月${date.getDate()}日`;
};
weeks.push({
year: year,
month: month + 1,
weekNumber: weekCounter,
text: `${year}年${month + 1}月第${weekCounter}周`,
saturdayDate: formatDate(saturday),
sundayDate: formatDate(sunday),
weekendDates: `${formatDate(saturday)}(周六),${formatDate(sunday)}(周日)`
});
weekCounter++;
}
// 移动到下一周
currentWeekStart.setDate(currentWeekStart.getDate() + 7);
}
return weeks;
}
// 获取当前月和下一个月的周数 const currentMonthWeeks = getWeeksInMonth(currentYear, currentMonth);
// 计算下个月 let nextYear = currentMonth === 11 ? currentYear + 1 : currentYear; let nextMonth = currentMonth === 11 ? 0 : currentMonth + 1; const nextMonthWeeks = getWeeksInMonth(nextYear, nextMonth);
// 合并所有周数 const allWeeks = [...currentMonthWeeks, ...nextMonthWeeks];
// 找到当前周 const now = new Date(); const currentWeek = allWeeks.find(week => { const weekStart = new Date(week.year, week.month - 1, 1); // 计算正确的周开始日期 const firstDayOfMonth = new Date(week.year, week.month - 1, 1); const dayOfWeek = firstDayOfMonth.getDay(); const dayOfWeekAdjust = dayOfWeek === 0 ? 7 : dayOfWeek; // 将周日转换为7
weekStart.setDate(1 + (week.weekNumber - 1) * 7 - (dayOfWeekAdjust - 1));
const weekEnd = new Date(weekStart);
weekEnd.setDate(weekStart.getDate() + 6);
return now >= weekStart && now <= weekEnd;
});
// 设置表单数据 var obj = {}; obj.d14 = currentWeek ? currentWeek.weekendDates : (allWeeks[0] ? allWeeks[0].weekendDates : '');
// 将weekOptions转化为[{id:1,name:'理想'},{id:2,name:'理想2'}]这种格式赋值给d15 const weekOptionsForD15 = allWeeks.map((week, index) => ({ id: week.text, name: week.text, weekendDates: week.weekendDates // 保存周末日期信息用于选择时更新d14 }));
this.$nextTick(() => { // 设置d15的选项列表 this.widgetRefList['d15'].optionList = weekOptionsForD15; this.setFormData(obj);
});