VUE中时间戳转换
2021-06-10 本文已影响0人
Henry01
1,在assets下创建一个date.js
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)
}
export {formatDate}
2,在组件中使用
引入 import { formatDate } from '../../assets/js/date.js';
export default {
//过滤
filters: {
formatDate(time) {
time = time * 1000 //注意:time应为格式为13位unix时间戳,如果是10位的unix时间戳,需要乘以1000
let date = new Date(time)
return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
}
},
}
DOM中写法:
<el-table-column prop="gmtCreate" label="时间" show-overflow-tooltip>
<template slot-scope="props">
<span>{{props.row.gmtCreate|formatDate}}</span>
</template>
</el-table-column>