element ui+vue使用filters格式化日期时间

定义日期格式化方法
目录:filters/index.js
/**
 * @desc 时间格式化
 *       将 2019-07-18T11:54:16.000+0000 格式化成类似 2019/07/18 11:54:16
 *       可以指定日期和时间分隔符
 * @param datetime 国际化日期格式
 */
export function formatDatetime (datetime) {
    if (datetime != null) {
        const dateMat = new Date(datetime);
        const year = dateMat.getFullYear();
        const month = (dateMat.getMonth() + 1 < 10 ? "0" + (dateMat.getMonth() + 1) : dateMat.getMonth() + 1);
        const day = dateMat.getDate() < 10 ? "0" + dateMat.getDate() : dateMat.getDate();
        const hh = dateMat.getHours() < 10 ? "0" + dateMat.getHours() : dateMat.getHours();
        const mm = dateMat.getMinutes() < 10 ? "0" + dateMat.getMinutes() : dateMat.getMinutes();
        const ss = dateMat.getSeconds() < 10 ? "0" + dateMat.getSeconds() : dateMat.getSeconds();
        var timeFormat = year + '/' + month + '/' + day + ' ' + hh + ':' + mm + ':' + ss;
        return timeFormat;
    }
}

/**
 * 格式化日期
 * 格式化成类似 2019-07-18
 */
export function formatDate (date) {
    if (date != null) {
        const dateMat = new Date(date);
        const year = dateMat.getFullYear();
        const month = (dateMat.getMonth() + 1 < 10 ? "0" + (dateMat.getMonth() + 1) : dateMat.getMonth() + 1);
        const day = dateMat.getDate() < 10 ? "0" + dateMat.getDate() : dateMat.getDate();
        const timeFormat =
            year + '-' + month + '-' + day;
        return timeFormat;
    }
}
在组件中引入,并通过过滤器使用:
import { formatDatetime, formatDate } from '@/filters/index'

//定义过滤器,与created、components等同一层级
  filters: {
    formatDateTime (value) {
      return formatDatetime(value)
    },
    formatDate(value){
      return formatDate(value)
    }
  },
// 在组件中使用:
<p>格式化时间:{{ value2 | formatDateTime }}</p>
<p>格式化日期:{{ value2 | formatDate }}</p>

//在表格中使用(格式化时间戳):
<el-table-column prop="datetime" label="时间" width="180">
  <template slot-scope="scope">
    {{scope.row.datetime | formatDateTime}}
  </template>
</el-table-column>
效果如下:(注:若时间戳格式话为1970年,说明时间戳单位为秒,修改为毫秒即可,即乘于1000)

在这里插入图片描述
完整代码

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值