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

html部分:

 
{{ currentTime.time }}

{{ currentTime.currentDay }}

{{ currentTime.date }}

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]
    }
  }

最终样式:

你可能感兴趣的:(笔记,vue.js,javascript,前端)