//初始化时间 调用方法
const initDate = () => {
const startDate = new Date('2024-01-11');
const endDate = new Date('2024-02-18');
getSelectMonths(startDate ,endDate )
}
getSelectMonths方法计算区间的日月周
const getSelectMonths = (startDate, endDate) => {
const startYear = startDate.getFullYear();
const startMonth = startDate.getMonth();
const endYear = endDate.getFullYear();
const endMonth = endDate.getMonth();
let currentYear = startYear;
let currentMonth = startMonth;
const months = [];
if (activeName.value === '周') {
let currentWeek = 1;
// 循环输出周期信息
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0');
const week = Math.ceil((currentDate.getDate() - currentDate.getDay() + 1) / 7);
console.log(`${year}-${month}-第${week + 1}周`);
currentDate.setDate(currentDate.getDate() + 7);
if (currentDate.getMonth() !== startDate.getMonth()) {
currentWeek = 1;
} else {
currentWeek++;
}
months.push(`${year}-${month}-第${week + 1}周`)
}
} else if (activeName.value === '日') {
// 循环遍历日期范围
let currentDate = new Date(startDate);
while (currentDate <= endDate) {
const year = currentDate.getFullYear();
const month = String(currentDate.getMonth() + 1).padStart(2, '0'); // 补零
const day = String(currentDate.getDate()).padStart(2, '0'); // 补零
const formattedDate = `${year + '年'}-${month + '月'}-${day + '日'}`;
months.push(formattedDate);
currentDate.setDate(currentDate.getDate() + 1);
}
} else {
while (currentYear < endYear || (currentYear === endYear && currentMonth <= endMonth)) {
const monthString = `${currentYear}-${(currentMonth + 1).toString().padStart(2, '0')}`;
months.push(monthString + '月份');
currentMonth++;
if (currentMonth > 11) {
currentMonth = 0;
currentYear++;
}
}
}
console.log(months, 'months');
}
效果图展示
日
周
月