1. vue过滤器,也可放到全局,就不用每个页面都写
<template>
<!-- time为时间戳 -->
<div>{{time | formatDate}}</div>
<!-- 结果为 2018-01-23 18:31:35 -->
</template>
export default {
data() {
return {
time: 1516703495241
};
},
filters: {
formatDate: function (value) {
let date = new Date(value);
let y = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? ('0' + MM) : MM;
let d = date.getDate();
d = d < 10 ? ('0' + d) : d;
let h = date.getHours();
h = h < 10 ? ('0' + h) : h;
let m = date.getMinutes();
m = m < 10 ? ('0' + m) : m;
let s = date.getSeconds();
s = s < 10 ? ('0' + s) : s;
return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}
}
}
2. 复杂业务使用 moment.js 或者 day.js
安装: cnpm install moment --save
vue中使用:
import moment from 'moment'
<div>{{dateBegin | formatDate}}</div>
filters: {
formatDate: function (value) {
return moment(value).format('YYYY-MM-DD')
}
},
submit() {
console.log(moment(this.dateBegin).format('YYYY-MM-DD'))
}