页面
<div><span style="margin-right: 4px;">{{nowDate }}</span><span class="houertime">{{ hourDate}}</span></div>
方法
export default {
data() {
return {
nowDate: null,
hourDate: null,
nowtimer: ''
}
},
created() {
this.gettime()
this.nowtimer = setInterval(this.gettime, 1000);
},
beforeDestroy () {
if (this.nowDate && this.hourDate) {
clearInterval(this.nowDate, this.hourDate) // 在Vue实例销毁前,清除定时器
}
},
methods: {
gettime() {
this.nowDate = new Date().toLocaleString('zh', { year: 'numeric', month: 'numeric', day: 'numeric' })
this.hourDate = new Date().toLocaleString('zh', { hour: 'numeric', minute: 'numeric', second: 'numeric' })
this.handleTimeFormat()
},
// 日期格式修改 由 **/**/**日期格式改为 **年**月**日
handleTimeFormat() {
const [year, month, day] = this.nowDate.split("/");
this.nowDate = `${year}年${month.padStart(2, '0')}月${day.padStart(2, '0')}日`;
}
}
}