el-date-picker 获取当前月往前推算3个月、6个月的日期

该博客围绕前端需求展开,要实现点击1个月、3个月、6个月时,el-date-picker控件分别显示当前月、当前月 - 3、当前月 - 6。还给出了当前月为2023 - 08时的显示示例,并提及了HTML和JS部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:实现点击1个月、3个月、6个月的时候,el-date-picker 控件分别显示当前月、当前月-3、当前月-6;

举例:当前月为2023-08,那么点击1个月时显示2023-08至2023-08,点击3个月显示2023-05至2023-08

点击6个月显示2023-02至2023-08 

HTML部分:

<div class="button">
     <el-button type="primary" @click="getMonthDate(1)">1个月</el-button>
     <el-button type="primary" @click="getMonthDate(3)">3个月</el-button>
     <el-button type="primary" @click="getMonthDate(6)">6个月</el-button>
</div>

 JS部分:

getMonthDate(time) {
    let year = new Date().getFullYear();
    let curMonth = new Date().getMonth() + 1;
    let month = curMonth >= 10 ? curMonth : "0" + curMonth
    if (time === 1) {
        this.searchTimes[0] = `${year}-${month}`;
        this.searchTimes[1] = `${year}-${month}`;
     }
     if (time === 3) {
        let oneMonth = curMonth - 3;
        this.searchTimes[0] = this.getDate(oneMonth);
        this.searchTimes[1] = `${year}-${month}`;
     }
     if (time === 6) {
         let oneMonth = curMonth - 6;
         this.searchTimes[0] = this.getDate(oneMonth);
         this.searchTimes[1] = `${year}-${month}`;
     }
},

 

getDate(month) {
   let date = new Date();
   let year = date.getFullYear();
   let newYear = 0;
   let newMonth = 0;
   if (month < 1) {
       newYear = year - 1;
       newMonth = month + 12 >= 10 ? month + 12 : '0' + (month + 12);
       return newYear + '-' + newMonth;
   } else {
        newMonth = month >= 10 ? month : '0' + (month);
        return year + '-' + newMonth;
   }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值