vue动态获取年月日时分秒

js片段


data() {
    return {
      nowTime:''
    };
  },

 created() {
    this.nowTimes()
  },
  methods: {
 timeFormate(timeStamp) {
      let year = new Date(timeStamp).getFullYear();
      let month =new Date(timeStamp).getMonth() + 1 < 10? "0" + (new Date(timeStamp).getMonth() + 1): new Date(timeStamp).getMonth() + 1;
      let date =new Date(timeStamp).getDate() < 10? "0" + new Date(timeStamp).getDate(): new Date(timeStamp).getDate();
      let hh =new Date(timeStamp).getHours() < 10? "0" + new Date(timeStamp).getHours(): new Date(timeStamp).getHours();
      let mm =new Date(timeStamp).getMinutes() < 10? "0" + new Date(timeStamp).getMinutes(): new Date(timeStamp).getMinutes();
      let ss =new Date(timeStamp).getSeconds() < 10? "0" + new Date(timeStamp).getSeconds(): new Date(timeStamp).getSeconds();
      let week = new Date(timeStamp).getDay();
      let weeks = ["日","一","二","三","四","五","六"];
      let getWeek = "星期" + weeks[week];
      this.nowTime = year + "年" + month + "月" + date +"日"+" "+hh+":"+mm+':'+ss+getWeek  ;
    },
    nowTimes(){
      this.timeFormate(new Date());
      setInterval(this.nowTimes,1000);
      this.clear()
      console.log(this.nowTime);
      
    },
    clear(){
      clearInterval(this.nowTimes)
      this.nowTimes = null;
    }
}

在这里插入图片描述

还有一种简单点的

 let _this = this; // 声明一个变量指向Vue实例this,保证作用域一致
    this.timer = setInterval(() => {
      let _this = this; // 声明一个变量指向Vue实例this,保证作用域一致
    this.timer = setInterval(() => {

      let hh =new Date( ).getHours()   < 10? "0" + new Date( ).getHours()  : new Date( ).getHours();
      let mm =new Date( ).getMinutes() < 10? "0" + new Date( ).getMinutes(): new Date( ).getMinutes();
      let ss =new Date( ).getSeconds() < 10? "0" + new Date( ).getSeconds(): new Date( ).getSeconds();
      _this.nowTime =new Date().toLocaleDateString()+" "+ hh+":"+mm+":"+ss
    




      // new Date().toLocaleDateString()+ "    "+new Date().toLocaleTimeString(); // 修改数据date
    }, 1000);
      _this.nowTime = new Date().toLocaleDateString()+ "    "+new Date().toLocaleTimeString(); // 修改数据date
    }, 1000);

在这里插入图片描述
在这里插入图片描述

你可能感兴趣的:(vue动态获取年月日时分秒)