日期选择器--格式化--快捷选项

日期:

复制代码
        <el-form-item label="检验时间:" prop="date">
          <el-date-picker
            v-model="queryParams.date"
            type="date"
            placeholder="请选择"
            clearable
            size="small"
            value-format="yyyy-MM-dd"
          />
        </el-form-item> 
复制代码

表格

复制代码
<el-table v-loading="loading" :data="tableData1">
          <template slot="empty">
            <div style="height: 500px">
              <img src="@/assets/image/zwsj.png" alt="" />
              <div
                style="
                  display: flex;
                  height: 32px;
                  align-items: center;
                  justify-content: center;
                "
              >
                <p style="color: #333; font-size: 14px">暂无数据</p>
              </div>
            </div>
          </template>
          <el-table-column prop="date" label="时间" :formatter="formatDateTime">
          </el-table-column>
</el-table>
复制代码

js

复制代码
// 日期格式转换
    formatDateTime(row) {
      const rawDateTime = row.date;
      if (rawDateTime) {
        const dateObj = new Date(rawDateTime);
        const year = dateObj.getFullYear();
        const month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
        const date = ("0" + dateObj.getDate()).slice(-2);
        const hours = ("0" + dateObj.getHours()).slice(-2);
        const minutes = ("0" + dateObj.getMinutes()).slice(-2);
        const seconds = ("0" + dateObj.getSeconds()).slice(-2);

        return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
      } else {
        return "";
      }
    },
复制代码

 

日期范围:

复制代码
    <el-date-picker
            v-model="timeRange"
            type="daterange"
            format="yyyy-MM-dd"
            placeholder="选择日期范围"
            @change="handleDateChange"
            style="width: 220px; margin-top: 6px"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
复制代码

 

复制代码
// 格式化日期为 yyyy-MM-dd
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份需要 +1,因为是从 0 开始的
      const day = String(d.getDate()).padStart(2, '0'); // 日期前补充 0
      return `${year}-${month}-${day}`;
    },
    // 时间范围变化时赋值给后端传参
    handleDateChange(value) {
      if (!value) {
        this.formData.startTime = '';
        this.formData.endTime = '';
        return;
      }
      if (value && value.length === 2) {
        this.formData.startTime = this.formatDate(value[0]);
        this.formData.endTime = this.formatDate(value[1]);
      }
    },
复制代码

 

带快捷选项的日期范围选择器

pickerOptions可以带disabledDate
复制代码
               <el-date-picker
                  v-model="outqueryParams.admissionTime"
                  type="daterange"
                  placeholder="请选择"
                  style="width: 240px"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions"
                  @change="handleDateChange"
                ></el-date-picker>    
复制代码

快捷选项:最近一周,最近一个月,最近三个月

复制代码
      // 日期范围快捷选项
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
复制代码

 

限制不能选择超过12个月

复制代码
    // 判断日期最大选择范围是否超过12个月
    handleDateChange(value) {
      if (value && value.length === 2) {
        const [startDate, endDate] = value;
        const start = new Date(startDate);
        const end = new Date(endDate);
        // 计算日期差距(毫秒为单位)
        const timeDifference = end - start;
        const monthDifference = timeDifference / (1000 * 3600 * 24 * 30); // 大致的月差(一个月30天)
        // 判断是否超过12个月
        if (monthDifference > 12) {
          this.$message.warning('可选的日期范围最大为12个月,请重新选择。');
          this.outqueryParams.admissionTime = []; // 清空选择的日期
        }
      }
    },
复制代码

 

判断日期选择器是否为空,为空则不在日期后面拼接 ' 00:00:00'或' 23:59:59'

复制代码
      // 初始化 queryParams 对象
      const queryParams = {
        jbxx: this.outqueryParams.jbxx,
        yjjb: this.outqueryParams.yjjb,
        ksdm: this.outqueryParams.ksdm,
        bqdm: this.outqueryParams.bqdm,
        pageNum: this.outqueryParams.pageNum,
        pageSize: this.outqueryParams.pageSize,
        startTime: '', // 初始化为 null 或其他默认值
        endTime: '' // 同上
      };

      // 检查 this.outqueryParams.admissionTime 是否存在且为数组且包含两个有效元素
      if (
        Array.isArray(this.outqueryParams.admissionTime) &&
        this.outqueryParams.admissionTime.length === 2
      ) {
        const [start, end] = this.outqueryParams.admissionTime;

        // 检查每个元素是否为 Date 对象或已经是 yyyy-mm-dd 格式的字符串
        let formattedStart = null;
        let formattedEnd = null;

        if (start instanceof Date) {
          formattedStart = start.toISOString().split('T')[0] + ' 00:00:00';
        } else if (
          typeof start === 'string' &&
          /^\d{4}-\d{2}-\d{2}$/.test(start)
        ) {
          formattedStart = start + ' 00:00:00';
        }

        if (end instanceof Date) {
          formattedEnd = end.toISOString().split('T')[0] + ' 23:59:59';
        } else if (typeof end === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(end)) {
          formattedEnd = end + ' 23:59:59';
        }

        // 如果两个时间都被成功格式化,则更新 queryParams
        if (formattedStart && formattedEnd) {
          queryParams.startTime = formattedStart;
          queryParams.endTime = formattedEnd;
        }
      }
复制代码

 

 

复制代码
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().toLocaleDateString());
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date(new Date().getTime() - 3600 * 1000 * 24);
              const start = new Date(new Date(end).toLocaleDateString());
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date(
                new Date().getTime() - 3600 * 1000 * 24 * 7
              );
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const year = new Date().getFullYear();
              const month = new Date().getMonth() + 1;
              const start = new Date(year, month - 1, 1);
              const end = new Date(year, month, 0);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '上月',
            onClick(picker) {
              const year = new Date().getFullYear();
              const month = new Date().getMonth();
              const lastMonth = month === 0 ? 11 : month - 1;
              const lastMonthDay = new Date(year, lastMonth + 1, 0).getDate();
              const start = new Date(year, lastMonth, 1);
              const end = new Date(year, lastMonth, lastMonthDay);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      }
复制代码

 

posted @   .Tik  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· [翻译] 为什么 Tracebit 用 C# 开发
· Deepseek官网太卡,教你白嫖阿里云的Deepseek-R1满血版
· DeepSeek崛起:程序员“饭碗”被抢,还是职业进化新起点?
· 2分钟学会 DeepSeek API,竟然比官方更好用!
· .NET 使用 DeepSeek R1 开发智能 AI 客户端
点击右上角即可分享
微信分享提示