<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>格式化时间</title>
<style>
#app{
font-weight: bold;
font-size: 20px;
}
</style>
</head>
<body>
<div id="app">
<div>{{timeOne}} ----> {{timeOne | format}}</div>
<div>{{timeTwo}} ----> {{timeTwo | format('MM-DD')}}</div>
<div>{{timeTwo}} ----> {{timeTwo | format('MM月DD日')}}</div>
<div>{{timeTwo}} ----> {{timeTwo | format('YYYY/MM/DD')}}</div>
<div>{{timeOne}} ----> {{timeTwo | format('YYYY-MM-DD')}}</div>
<div>{{timeTwo}} ----> {{timeTwo | format('YYYY/MM/DD HH:mm:ss 星期w')}}</div>
<div>{{timeTwo}} ----> {{timeTwo | format('YYYY-MM-DD 星期w')}}</div>
<div>{{timeOne}} ----> {{timeTwo | format('YYYY年MM月DD日 星期w')}}</div>
<div>时间戳:{{timeThree}} ----> {{timeThree | format('YYYY')}}</div>
<div>时间戳:{{timeThree}} ----> {{timeThree | format('YYYY-MM')}}</div>
<div>时间戳:{{timeThree}} ----> {{timeThree | format('YYYY-MM-DD HH:mm')}}</div>
<div>时间戳:{{timeThree}} ----> {{timeThree | format('YYYY年MM月DD日')}}</div>
<div>时间戳:{{timeThree}} ----> {{timeThree | format('YYYY年MM月DD日 星期w')}}</div>
<div>时间戳:{{timeThree}} ----> {{timeThree | format('YYYY年MM月DD日 HH时mm分')}}</div>
</div>
</body>
</html>
<script src="vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
timeOne: '2021/07/17 14:20:00',
timeTwo: '2021-07-17 14:20:50',
timeThree: 1626500149311
},
filters: {
format(time, format = 'YYYY-MM-DD HH:mm:ss') {
let date = new Date(time)
let o = {
'M+': date.getMonth() + 1,
'D+': date.getDate(),
'H+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds(),
'w': '日一二三四五六'.charAt(date.getDay())
};
format = format.replace(/Y{4}/, date.getFullYear()).replace(/Y{2}/, date.getFullYear().toString().substring(2));
let k, reg
for (k in o) {
reg = new RegExp(k);
format = format.replace(reg, match);
}
function match(m) {
return m.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length);
}
return format;
}
}
})
</script>

|