<template>
<div>
{{nowDate}}{{nowWeek}}{{nowTime}}
//{{formatDateTime}}
</div>
</template>
<script>
export default {
data(){
return {
nowDate: "", // 当前日期
nowTime: "", // 当前时间
nowWeek: "" // 当前星期
//formatDateTime:"", //当前总时间
}
},
methods:{
dealWithTime(data) { // 获取当前时间
//年
let year = data.getFullYear();
//月
let month = data.getMonth() + 1;
//日
let date = data.getDate();
//时
let hours = data.getHours();
//分
let minutes = data.getMinutes();
//秒
let seconds = data.getSeconds();
//周几
let W = data.getDay();
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
switch (W) {
case 0:
W = "日";
break;
case 1:
W = "一";
break;
case 2:
W = "二";
break;
case 3:
W = "三";
break;
case 4:
W = "四";
break;
case 5:
W = "五";
break;
case 6:
W = "六";
break;
default:
break;
}
this.nowDate = year + "年" + month + "月" + date + "日 ";
this.nowWeek = "周" + W ;
this.nowTime = hours + ":" + minutes + ":" + seconds;
// formatDateTime = year + "年" + month + "月" + date + "日 " + " 周" +W + hours + ":" + minutes + ":" + seconds;
},
},
mounted() {
// 页面加载完后显示当前时间
this.dealWithTime(new Date())
// 定时刷新时间
this.timer = setInterval(()=> {
this.dealWithTime(new Date()) // 修改数据date
}, 500)
},
destroyed() {
if (this.timer) { // 注意在vue实例销毁前,清除我们的定时器
clearInterval(this.timer);
}
}
}
</script>
<style lang="scss" scope>
</style>
vue 获取当前时间
最新推荐文章于 2024-08-29 10:13:47 发布
该博客主要展示了如何在Vue.js应用中获取并格式化当前日期、时间及星期。通过`dealWithTime`方法获取年、月、日、时、分、秒以及星期,并根据星期的数字转换为中文表示。在页面加载时初始化时间显示,并使用定时器每500毫秒更新时间。此外,还考虑了在组件销毁时清理定时器,确保资源的释放。
摘要由CSDN通过智能技术生成