美文网首页
Element UI表格组件的时间格式器

Element UI表格组件的时间格式器

作者: microkof | 来源:发表于2020-09-01 17:56 被阅读0次

前言

在表格中经常会展示时间,此时我们就需要一个时间格式器将后端传来的若干种时间数据转换成高可读时间,因此我写了一个格式器:

代码

一个mixin搞定,请全局引入:

export default {
  install(Vue) {
    Vue.mixin({
      methods: {
        timeFormatter(row, column, cellValue, index, pattern) {
          if (!cellValue) {
            return '';
          }
          const format = pattern || 'y-m-d h:i:s'
          let date
          if (typeof cellValue === 'object') {
            date = cellValue
          } else {
            // 下面2个 if 考虑到了cellValue可能不是数字类型时间戳以及可能不是毫秒级时间戳
            if ((typeof cellValue === 'string') && (/^[0-9]+$/.test(cellValue))) {
              cellValue = parseInt(cellValue)
            }
            if ((typeof cellValue === 'number') && (cellValue.toString().length === 10)) {
              cellValue = cellValue * 1000
            }
            date = new Date(cellValue)
          }
          const formatObj = {
            y: date.getFullYear(),
            m: date.getMonth() + 1,
            d: date.getDate(),
            h: date.getHours(),
            i: date.getMinutes(),
            s: date.getSeconds(),
            a: date.getDay()
          }
          const time_str = format.replace(/(y|m|d|h|i|s|a)+/g, (result, key) => {
            let value = formatObj[key]
            if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
            if (result.length > 0 && value < 10) {
              value = '0' + value
            }
            return value || 0
          })
          return time_str
        },
      }
    })
  }
}

用法

只要年月日:

<el-table-column label="安装日期" prop="createTime" :formatter="(...rest)=>timeFormatter(...rest, 'y-m-d')" />

年月日小时分钟:

<el-table-column label="安装日期" prop="createTime" :formatter="(...rest)=>timeFormatter(...rest, 'y-m-d h:i')" />

年月日星期:

<el-table-column label="安装日期" prop="createTime" :formatter="(...rest)=>timeFormatter(...rest, 'y-m-d 星期a')" />

默认格式(年月日小时分钟秒钟):

<el-table-column label="安装日期" prop="createTime" :formatter="timeFormatter" />

相关文章

网友评论

      本文标题:Element UI表格组件的时间格式器

      本文链接:https://www.haomeiwen.com/subject/jophsktx.html