日照網(wǎng)站推廣今日熱榜
以下代碼可以實(shí)現(xiàn)獲取當(dāng)前時(shí)間并實(shí)時(shí)顯示,朋友們直接copy使用即可,希望可以幫助到有需要的朋友們!
<template><div class="time">{{ datetimeStr }}</div>
</template>
<script>export default {data() {return {datetimeStr: '', // 顯示當(dāng)前時(shí)間formatDate: null, // 定時(shí)器}}}mounted() {this.updateDateTime();this.formatDate = setInterval(() => {this.updateDateTime();}, 1000);}unmounted() { // 在Vue實(shí)例銷毀前,清除時(shí)間定時(shí)器if (this.formatDate) {clearInterval(this.formatDate);}}methods: {updateDateTime() { // 格式化需要展示的時(shí)間格式const now = new Date();const year = now.getFullYear();let month = now.getMonth() + 1;let day = now.getDate();const weekday = now.getDay();let hours = now.getHours();let minutes = now.getMinutes();let seconds = now.getSeconds();// 將月份和日期補(bǔ)零month = month < 10 ? '0' + month : month;day = day < 10 ? '0' + day : day;hours = hours < 10 ? '0' + hours : hours;minutes = minutes < 10 ? '0' + minutes : minutes;seconds = seconds < 10 ? '0' + seconds : seconds;// 星期數(shù)組const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];// 格式化日期時(shí)間this.datetimeStr = year + "年" + month + "月" + day + "日 " + weekdays[weekday] + " " + hours + ":" + minutes + ":" + seconds;}}}
</script>