Custom formatting time
One, the problem
This is a product list page in a background management system. After calling the interface, you will find that the time is calculated in milliseconds. Of course, this is not possible. It should be converted to our daily use 2020-04-07 17:13 This time format
Two, the solution
1. Open the main.js file in the project and
register a global filter, the name can be customized, I use'dateFormat' here
//对名称进行定义,提供一个function函数 originVal 为形参
Vue.filter('dateFormat',function(originVal){
const dt = new Date(originVal)
//年的时间
const y = dt.getFullYear()
//月的时间 .padStart 不足两位自动补0 2位长度
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 'yyyy-mm-dd hh:mm:ss' 可以改成下面的方法
return `${
y}-${
m}-${
d} ${
hh}:${
mm}:${
ss}`
})
2. Render the
time, find the place where the time is defined, and introduce it through the scope slot
The label "name"
prop is the data object
slot-scop in the binding interface to receive the data in the slot
dateFormat format the name of the time filter
<el-table-column label='创建时间' prop="add_time" width="170px">
<template slot-scope="scope">
{
{scope.row.add_time | dateFormat}}
</template>
</el-table-column>
Below is a screenshot of the code:
The renderings are as follows:
—————————————————— 补充说明 ——————————————————
由于之前没有注意,检查项目时发现由时间戳转换为年月日进制时导致时间为1970年,
改正后的代码如下:在originVal 后面*1000即可
the reason:这是因为在转换时原来的时间戳是为毫秒,转换为年月日后就会为1970的年,可以在毫秒后面*1000 这样即可完成转换了
Vue.filter('dateFormat',function(originVal){
const dt = new Date(originVal*1000)
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}`
})
Effect picture after correction: