vue实现获取系统当前年月日时分秒星期

(壹)博主介绍

个人博客: 尔滨三皮
⌛程序寄语:木秀于林,风必摧之;行高于人,众必非之。

(贰)文章内容

img


<template>
  <div class="currentTimeBox">
    <p>{{ nowDate + " " + nowTime + " " + nowWeek }}p>
  div>
template>
<script>
export default {
  data() {
    return {
      nowDate: "", // 当前日期
      nowTime: "", // 当前时间
      nowWeek: "", // 当前星期
    }
  },
  mounted() {
    this.currentTime()
  },
  methods: {
    currentTime() {
      setInterval(this.getDate, 500)
    },
    getDate() {
      var _this = this
      let yy = new Date().getFullYear()
      let mm = new Date().getMonth() + 1
      let dd = new Date().getDate()
      let week = new Date().getDay()
      let hh = new Date().getHours()
      let ms = new Date().getSeconds() < 10 ? "0" + new Date().getSeconds() : new Date().getSeconds()
      let mf = new Date().getMinutes() < 10 ? "0" + new Date().getMinutes() : new Date().getMinutes()
      if (week == 1) {
        this.nowWeek = "星期一"
      } else if (week == 2) {
        this.nowWeek = "星期二"
      } else if (week == 3) {
        this.nowWeek = "星期三"
      } else if (week == 4) {
        this.nowWeek = "星期四"
      } else if (week == 5) {
        this.nowWeek = "星期五"
      } else if (week == 6) {
        this.nowWeek = "星期六"
      } else {
        this.nowWeek = "星期日"
      }
      _this.nowTime = this.fillZero(hh) + "时" + mf + "分" + ms + "秒"
      _this.nowDate = this.fillZero(yy) + "年" + this.fillZero(mm) + "月" + this.fillZero(dd) + "日"
    },
    // 给时间补零
    fillZero(str) {
      var realNum
      if (str < 10) {
        realNum = "0" + str
      } else {
        realNum = str
      }
      return realNum
    },
  },
  // 销毁定时器
  beforeDestroy() {
    if (this.getDate) {
      console.log("销毁定时器")
      clearInterval(this.getDate) // 在Vue实例销毁前,清除时间定时器
    }
  },
}
script>

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