1. 背景
如果直接在浏览器中输出时间 Date 对象,你可能会得到这样的输出:
Thu Dec 26 2019 10:55:55 GMT+0800 (中国标准时间)
这种方式显然不符合阅读习惯,通常需要格式化。
2. 方式
2.1 函数预处理(格式化函数)
比较传统的 js 方法
function formatDate (date) {
let yyyy = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? '0' + MM : MM ;
let dd = date.getDate();
dd = dd < 10 ? '0' + dd : dd ;
let HH = date.getHours();
HH = HH < 10 ? '0' + HH : HH ;
let mm = date.getMinutes();
mm = mm < 10 ? '0' + mm : mm ;
let ss = date.getSeconds();
ss = ss < 10 ? '0' + ss : ss ;
let SSS = date.getMilliseconds();
if(SSS < 10) {
SSS = '00' + SSS;
} else if(SSS < 100) {
SSS = '0' + SSS;
}
return `${yyyy}/${MM}/${dd} ${HH}:${mm}:${ss}:${SSS}`;
}
2.2. Vue 过滤器
在 Vue 中定义过滤器函数
new Vue({
...
filters: {
formatDate: function(date) {
let yyyy = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? '0' + MM : MM ;
let dd = date.getDate();
dd = dd < 10 ? '0' + dd : dd ;
let HH = date.getHours();
HH = HH < 10 ? '0' + HH : HH ;
let mm = date.getMinutes();
mm = mm < 10 ? '0' + mm : mm ;
let ss = date.getSeconds();
ss = ss < 10 ? '0' + ss : ss ;
let SSS = date.getMilliseconds();
if(SSS < 10) {
SSS = '00' + SSS;
} else if(SSS < 100) {
SSS = '0' + SSS;
}
return `${yyyy}/${MM}/${dd} ${HH}:${mm}:${ss}:${SSS}`;
}
},
...
});
在 {{}} 插值的尾部添加管道符 "|" 对数据进行过滤,可以用于格式化文本,如字母全部大写,货币千位使用逗号分隔。
{{ date | formatDate }}
2.3. Vue 计算属性
顺便一提,Vue 计算属性不仅可以依赖一条数据,甚至可以依赖多条数据,只要其中任一变化,计算属性就会重新执行。
new Vue({
...
computed: {
formatDate: function() {
let yyyy = this.date.getFullYear();
let MM = this.date.getMonth() + 1;
MM = MM < 10 ? '0' + MM : MM ;
let dd = this.date.getDate();
dd = dd < 10 ? '0' + dd : dd ;
let HH = this.date.getHours();
HH = HH < 10 ? '0' + HH : HH ;
let mm = this.date.getMinutes();
mm = mm < 10 ? '0' + mm : mm ;
let ss = this.date.getSeconds();
ss = ss < 10 ? '0' + ss : ss ;
let SSS = this.date.getMilliseconds();
if(SSS < 10) {
SSS = '00' + SSS;
} else if(SSS < 100) {
SSS = '0' + SSS;
}
return `${yyyy}/${MM}/${dd} ${HH}:${mm}:${ss}:${SSS}`;
}
},
...
});
注意:这里的 this.date 是 data 属性里的数据,一定要声明成 date: new Date(),而不是 date: '' 或 date: 123 之类,否则报错。