vue 实时刷新年月日时分秒 及星期几

2023-12-21 16:20:00

html部分:

 <div class="right-time">
        <div class="time-box1">{{ currentTime.time }}</div>
        <div class="time-box2">
          <p>{{ currentTime.currentDay }}</p>
          <p>{{ currentTime.date }}</p>
        </div>

script:

 data() {
    return {
      currentTime: {
        time: '',
        date: '',
        currentDay:''
      },
    }
  },
  mounted () {
    setInterval(() => {
      this.updateTime()
    }, 1000)
  },
  methods: {
    updateTime () {
      const dateObj = new Date()
      const hours = dateObj.getHours()
      const minutes = dateObj.getMinutes()
      const seconds = dateObj.getSeconds()
      // 格式化小时、分钟、秒数
      const hours1 = hours < 10 ? '0' + hours : hours
      const minutes1 = minutes < 10 ? '0' + minutes : minutes
      const seconds1 = seconds < 10 ? '0' + seconds : seconds
      const year = dateObj.getFullYear()
      const month = dateObj.getMonth() + 1
      const day = dateObj.getDate()
      // 格式化月、日
      const month1 = month < 10 ? '0' + month : month
      const day1 = day < 10 ? '0' + day : day
      const day2 = dateObj.getDay()
      this.currentTime.currentDay = this.getDayName(day2)
      this.currentTime.time = `${hours1}:${minutes1}:${seconds1}`
      this.currentTime.date = `${year}/${month1}/${day1}`
      console.log('111', this.currentTime)
    },
    getDayName(day) {
      const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
      return days[day]
    }
  }

最终样式:

文章来源:https://blog.csdn.net/paradoxaaa_/article/details/135124732
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。