Vue获取实时时间并按需求格式化

暂时记录一下代码,有空时再详细标注。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<template>
<div class="home">
<div class="showTime">
{{ dateFormat(date) }}
</div>
</div>
</template>

<script>
export default {
name: "Home",
methods: {
dateFormat(time) {
var date = new Date(time);
var year = date.getFullYear();
var month =
date.getMonth() + 1 < 10
? "0" + (date.getMonth() + 1)
: date.getMonth() + 1;
var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var hours =
date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes =
date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var seconds =
date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
return (
year +
"-" +
month +
"-" +
day +
" " +
hours +
":" +
minutes +
":" +
seconds
);
}
},
data() {
return {
date: new Date()
};
},
mounted() {
var _this = this;
this.timer = setInterval(function() {
_this.date = new Date();
}, 1000);
},
beforeDestroy: function() {
if (this.timer) {
clearInterval(this.timer);
}
}
};
</script>