您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页vue实现获取当前时间并实时显示

vue实现获取当前时间并实时显示

来源:五一七教育网
<template>
  <div class="time">{{ datetimeStr }}</div>
</template>
<script>
  export default {
    data() {
      return {
        datetimeStr: '', // 显示当前时间
        formatDate: null, // 定时器}
      }
    }
    mounted() {
      this.updateDateTime();
      this.formatDate = setInterval(() => {
        this.updateDateTime();
      }, 1000);
    }
    unmounted() { // 在Vue实例销毁前,清除时间定时器
      if (this.formatDate) {
        clearInterval(this.formatDate);
      }
    }
    methods: {
      updateDateTime() { // 格式化需要展示的时间格式
        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();
        
        // 将月份和日期补零
        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;
        
        // 星期数组
        const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    
        // 格式化日期时间
        this.datetimeStr = year + "年" + month + "月" + day + "日 " + weekdays[weekday] + " " + hours + ":" + minutes + ":" + seconds;
      }
    }
  }
</script>

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务