需求:在项目中将后台传回来的时间戳转换为 年-月-日 时:分:秒 如:2021-08-09 16:07:18
1.首先在main.js中添加一个全局过滤器,命名为dateFormat
Vue.filter('dateFormat', function (originVal) {
const dt = new Date(originVal)
const y = dt.getFullYear()
const m = (dt.getMonth() + 1 + '').padStart(2, '0')
const d = (dt.getDate() + '').padStart(2, '0')
const hh = (dt.getHours() + '').padStart(2, '0')
const mm = (dt.getMinutes() + '').padStart(2, '0')
const ss = (dt.getSeconds() + '').padStart(2, '0')
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`
})
- originVal为待处理的时间戳
- dt为获取到的日期对象
- getMonth()方法返回的是一个从0开始的数,所以加1
- +' ' : 可将数值转换为字符串从而可调用字符串的方法
- padStart()方法用于时间首位补0,即不足2位用0在首位作补充
- return返回拼接的字符串
2.调用
<template v-slot="slot">
{{ slot.row.add_time | dateFormat }}
</template>