使用element日期组件,实现固定日期为三个月

使用element组件

view层

       <el-date-picker
                      v-model="dataValue.value1"
                      type="month"
                      placeholder="选择月"
                      :clearable="false"
                      @change="getValue1(dataValue.value1)"
                    >
                    </el-date-picker
                    >至
                    <el-date-picker
                      class="picker2"
                      v-model="dataValue.value2"
                      type="month"
                      placeholder="选择月"
                      :clearable="false"
                      @change="getValue2(dataValue.value2)"
                    >
                    </el-date-picker> 

data中赋值,实现初始默认为当前月到之前3个月,例如2024-05-01到2024-07-31 

const now = new Date();
    const currentMonthLastDay = new Date(
      now.getFullYear(),
      now.getMonth() + 1,
      0
    ).getTime(); // 当前月的最后一天
    const threeMonthsAgoFirstDay = new Date(
      now.getFullYear(),
      now.getMonth() - 2,
      1
    ).getTime(); // 三个月前的1号
把这个两个值,分别赋给
  dataValue: {
         value1: threeMonthsAgoFirstDay,
         value2: currentMonthLastDay,
       },

methods层,首先监听并得到月份,至于日是不对的,我们需要 this.dataValue.value2为最后一日

    getValue1(newVal) {
       this.updateValue2(newVal);
    },
    getValue2(newVal) {
      this.updateValue1(newVal);
    },
    updateValue2(newValue1) {
      const newDate = new Date(newValue1);
      newDate.setMonth(newDate.getMonth() + 3);
      newDate.setDate(0);
      this.dataValue.value2 = newDate.getTime();
    },
    updateValue1(newValue2) {
      const newDate = new Date(newValue2);
      newDate.setMonth(newDate.getMonth() - 2);
      this.dataValue.value1 = newDate.getTime();
    },

在使用接口传递数据时,应该进行操作一下 

       startDate: formatDate(
          new Date(this.dataValue[0]).getTime(),
          "yyyy-MM-01 00:00:00"
        ),
        endDate: this.formatEndDate(new Date(this.dataValue[1])),

具体操作,使用这个方法即可实现获取最后一日。

    //获取年
    getYearMonthFromTimestamp(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      return { year, month };
    },
    //获取月
    getLastDayOfMonth(year, month) {
      return new Date(year, month, 0).getDate();
    },
    //获取最后一日
    formatEndDate(date) {
      const yearMonth = this.getYearMonthFromTimestamp(date);
      const lastDay = this.getLastDayOfMonth(yearMonth.year, yearMonth.month);
      return `${yearMonth.year}-${String(yearMonth.month).padStart(
        2,
        "0"
      )}-${lastDay} 23:59:59`;
    },

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值