Skip to content
泠泠彻夜的笔记
Main Navigation首页笔记
HTML
CSS
JavaScript
TypeScript
Node.js
Vue3
uniapp
插件
算法题

外观

blogs

时间格式转换踩坑

怡然

532字约2分钟

Javascriptelement-ui

2024-11-21

相关信息

开发时遇到,页面对用户展示为选择年月范围的时间组件,但是后端接口需要的参数为yyyy-MM-dd格式的时间,对于elementui中的日期范围组件,如果是monthRange,value-format属性设置为yyyy-MM-dd,默认带出的时间为开始月份的1日到结束月份的1日,显然这不符合查询条件,用户需要查询的是开始月份的1日到结束月份的最后一天。于是在选择日期变化的时候手动设置结束日期为最后一天,方法如下:

<template>
  <div>
    <el-date-picker
      v-model="query.date"
      type="monthrange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      value-format="yyyy-MM-dd"
      @change="handleDateChange"
      clearable
    ></el-date-picker>
  </div>
</template>
<script>
export default{
  data(){
    return{
      query:{
        date:[]
      }
    }
  },
  methods:{
    handleDateChange(dates) {
      if (dates && dates.length === 2) {
        const startMonth = new Date(dates[0]);
        const endMonth = new Date(dates[1]);

        // 获取结束月份的最后一天
        const lastDay = new Date(
          endMonth.getFullYear(),
          endMonth.getMonth() + 1,
          0
        ); // 获取的日期为最后一天的00:00:00
        this.query.date = [
          startMonth.toISOString().split("T")[0],
          lastDay.toISOString().split("T")[0],
        ];
      }
    },
  }
}
</script>

一开始我们采用这样的方法,new Date()里传值,只传到日,时分秒未传值,默认时分秒为00:00:00,这样在采用toISOString()方法,将标准时间格式转为yyyy-MM-ddTHH:mm:ss格式时,会默认将最后一天转为倒数第二天。

比如:选中的是10月,标准日期为Thu Oct 31 2024 00:00:00 GMT+0800 (中国标准时间),看似是10月31日,但是使用toISOString()后,日期就变成了2024-10-30。每个月份都会如此。

经过排查,发现是时分秒的问题,传值时将时分秒时间传为23:59:59,则会转换为最后一天。正确方法如下:

handleDateChange(dates) {
  if (dates && dates.length === 2) {
    const startMonth = new Date(dates[0]);
    const endMonth = new Date(dates[1]);

    // 获取结束月份的最后一天
    const lastDay = new Date(
      endMonth.getFullYear(),
      endMonth.getMonth() + 1,
      0,23,59,59
    ); // 获取的日期为最后一天的23:59:59
    this.query.date = [
      startMonth.toISOString().split("T")[0],
      lastDay.toISOString().split("T")[0],
    ];
  }
}
贡献者: tsxwslk
上一页排名图表展示
下一页面试总结Vue部分

Power by VuePress & vuepress-theme-plume