1.全局js
1.1 在common目录下新建date.js
export 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);
};
vue中引入
import { formatDate } from '../../../components/common/date.js'
定义filter
data() {
},
filters: {
formatDate (time) {
if(time!=null && time != undefined){
let date = new Date(time);
return formatDate(date, 'yyyy-MM-dd hh:mm:ss');
}
},
},
1.2.应用
div,span等中应用
<div class="date">{{item.pass_time | formatDate}}</div>
<span> {{ isActive | formatDate }} </span>
table中应用
<el-table-column prop="createTime" label="时间" >
<template slot-scope="scope">
{{scope.row.createTime | formatDate}}
</template>
</el-table-column>
2. 局部页面列表中时间列格式化
2.1 vue页面
<el-table-column label="更新时间" prop="updateTime" :formatter="formatDate"/>
2.2 vue中js
formatDate(row, column){
let date = row[column.property]
console.log(date);
let d = new Date(date);
let month = (d.getMonth() + 1) < 10 ? '0'+(d.getMonth() + 1) : (d.getMonth() + 1);
let day = d.getDate()<10 ? '0'+d.getDate() : d.getDate();
let hours = d.getHours()<10 ? '0'+d.getHours() : d.getHours();
let min = d.getMinutes()<10 ? '0'+d.getMinutes() : d.getMinutes();
let sec = d.getSeconds()<10 ? '0'+d.getSeconds() : d.getSeconds();
let times=d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec;
console.log(times);
return times;
}
3.局部页面列表时间字段格式化
<el-table-column label="更新时间" min-width="100" />
<template slot-scope="scope">
<span class="timeCenter">{{ scope.row.updateTime && moment(parseInt(scope.row.updateTime)).format('YYYY-MM-DD HH:ss:mm') }}</span>
</template>
</el-table-column>
4. 格式化
image.png//vue
<el-table-column label="CreateTime" min-width="150" prop="createTime" align="center" >
<template slot-scope="scope">{{ scope.row.createTime==null?'':formatDate_only(scope.row.createTime) }} </template>
</el-table-column>
//js
formatDate_only(date){
let d = new Date(date);
let month = (d.getMonth() + 1) < 10 ? '0'+(d.getMonth() + 1) : (d.getMonth() + 1);
let day = d.getDate()<10 ? '0'+d.getDate() : d.getDate();
let hours = d.getHours()<10 ? '0'+d.getHours() : d.getHours();
let min = d.getMinutes()<10 ? '0'+d.getMinutes() : d.getMinutes();
let sec = d.getSeconds()<10 ? '0'+d.getSeconds() : d.getSeconds();
let times=d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec;
return times;
},
网友评论