解决element-ui DateTimePicker 默认日期格式化问题

 需求是希望一进来默认展示当前时间的前一个月数据,以下是处理的方式
image.png

背景原因

使用的 element-ui 库中的日期时间选择器,首次进入页面,会给个默认的时间(30天时间段),这时候,拿到的日期并不是很理想,看以下描述:

<el-date-picker class="invoice-query-item"
    v-model="dataVal"
    type="datetimerange"
    @change="getInvoiceData"
    format="yyyy-MM-dd HH:mm:ss"
    value-format="yyyy-MM-dd HH:mm:ss"
    start-placeholder="开始日期"
    end-placeholder="结束日期">
</el-date-picker>

我们只有触发 change,拿到的日期会进行格式化,跟 value-format 的值绑定的一样。但是首次进来默认选定的日期并没有格式化。

// 首次拿到的日期格式
2019-02-10T11:21:25.346Z

// 触发change 后拿到的日期格式
2019-02-10 19:21:25

 

解决办法

其实就是格式化日期咯~,直接看代码:

// util.js
export function formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};

function padLeftZero(str) {
    return ('00' + str).substr(str.length);
}

// App.vue 页面引入这个方法
import { formatDate } from './util'
const invoice_end = new Date();
const invoice_start = new Date();
invoice_start.setTime(invoice_start.getTime() - 3600 * 1000 * 24 * 30);

export default {
  data() {
      return {
        dataVal: [formatDate(invoice_start, "yyyy-MM-dd hh:mm:ss"), formatDate(invoice_end, "yyyy-MM-dd hh:mm:ss")],
      }
  }
}

 

转载至:https://www.jianshu.com/p/7e4147e84469

posted @ 2020-03-20 17:14  他她  阅读(5879)  评论(0编辑  收藏  举报