vue 获取当前时间并自动刷新
新增需求,需要在大屏的右上角展示当前时间,并实时按秒刷新,通过通义千问搜索关键js代码后,整理出如下代码。
【效果图】
【HTML】
<div class="time-wrap">
{{ formattedDateTime }}
<span> {{ weekTime }}</span>
</div>
【script】
data() {
return {
formattedDateTime: '',
weekTime: '',
}
},
mounted() {
// 在组件挂载后立即更新时间显示
this.getFormattedDateTime();
// 设置定时器,每秒更新一次时间显示
setInterval(() => {
this.getFormattedDateTime();
}, 1000);
},
methods: {
// 时间展示
getFormattedDateTime() {
const now = new Date();
// 获取年月日
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需加1
const day = String(now.getDate()).padStart(2, '0');
// 获取时分秒
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
// 星期几,数组下标0对应星期天
const weekDays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const weekDay = weekDays[now.getDay()];
// 拼接字符串
this.formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
this.weekTime = `${weekDay}`;
}
}