vue3 ts 根据elementplus日期控件算出开始时间和结束时间区间的日周月

//初始化时间 调用方法

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');

}

 效果图展示

 月

  • 15
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值