html代码:
<div>{{ nowDate }}{{ nowTime }}</div>
js代码:
created() {
this.timer = setInterval(this.getTime, 1000);
},
beforeDestroy() {
if (this.timer) {
clearInterval(this.timer); // 在Vue实例销毁前,清除定时器
}
},
//方法
getTime() {
const date = new Date();
const year = date.getFullYear();
const month = date.getMonth() + 1;
const wk = date.getDay();
let weeks = [
"星期日",
"星期一",
"星期二",
"星期三",
"星期四",
"星期五",
"星期六"
];
let week = weeks[wk];
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const str = "";
if (this.hour > 12) {
this.hour -= 12;
this.str = " AM";
} else {
this.str = " PM";
}
this.month = check(month);
this.nowWeek = week;
this.day = check(day);
this.hour = check(hour);
this.minute = check(minute);
this.second = check(second);
function check(i) {
const num = i < 10 ? "0" + i : i;
return num;
}
this.nowDate =
year + "/" + this.month + "/" + this.day + "" + this.nowWeek;
this.nowTime = this.hour + ":" + this.minute + ":" + this.second;
},