Element-UI 时间选择器日期处理方法简单方便

133 阅读1分钟

Element-UI 时间选择器日期处理方法简单方便

日期框架构

image.png

<div class="blok">
  <div class="timer">
    <el-date-picker
      v-model="value1"
      @change="pickadd"
      type="datetimerange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
    >
    </el-date-picker>
    <el-button type="primary" icon="el-icon-search" @click="handleSearch"
      >查询</el-button
    >
  </div>
</div>

当我们点击确定时会触发这个方法

pickadd (value) {
  // 找到对应的开始日期 结束日期
  const startDate = new Date(value[0])
  const endDate = new Date(value[1])
  // 将日期对象转换为年月日字符串
  const startFormattedDate = this.formatDate(startDate)
  const endFormattedDate = this.formatDate(endDate)
  console.log("开始日期:", startFormattedDate)
  console.log("结束日期:", endFormattedDate)
},

时间戳转换方法

formatDate (date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份是从0开始计数的,需要加1
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
},

复制粘贴即可,所有选择器通用

最终效果

image.png