vue 获取当前时间

该博客主要展示了如何在Vue.js应用中获取并格式化当前日期、时间及星期。通过`dealWithTime`方法获取年、月、日、时、分、秒以及星期,并根据星期的数字转换为中文表示。在页面加载时初始化时间显示,并使用定时器每500毫秒更新时间。此外,还考虑了在组件销毁时清理定时器,确保资源的释放。
摘要由CSDN通过智能技术生成
<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值