Vue中可动态变化的 (年月日时分秒星期) 时间元素

5 篇文章 1 订阅

一、思路

在JavaScript中,Date对象用来表示日期和时间。
要获取系统当前时间,用:

var now = new Date();
now; // Wed Jun 24 2015 19:49:22 GMT+0800 (CST)
now.getFullYear(); // 2015, 年份
now.getMonth(); // 5, 月份,注意月份范围是0~11,5表示六月
now.getDate(); // 24, 表示24号
now.getDay(); // 3, 表示星期三
now.getHours(); // 19, 24小时制
now.getMinutes(); // 49, 分钟
now.getSeconds(); // 22, 秒
now.getMilliseconds(); // 875, 毫秒数
now.getTime(); // 1435146562875, 以number形式表示的时间戳

这个部分获取的Date是不可以动态改变的
为了使其可动态变化,我设置了一个一秒钟的定时器,每一秒获取一次Date对象、更新保存的数据。界面销毁时,销毁该定时器。

二、注意事项

1、当前时间是浏览器从本机操作系统获取的时间,所以不一定准确,因为用户可以把当前时间设定为任何值。
2、一个需要注意的地方,就是JavaScript的月份范围用整数表示是0~11(从0开始),其他的都不是。所以月份要加1

三、代码部分

<template>
 <div>{{date.year}}{{this.date.month}}{{this.date.date}}日,{{this.date.hours}}{{this.date.minutes}}{{this.date.seconds}}秒,
              <label v-if="this.date.day==1" for="">星期一</label>
              <label v-if="this.date.day==2" for="">星期二</label>
              <label v-if="this.date.day==3" for="">星期三</label>
              <label v-if="this.date.day==4" for="">星期四</label>
              <label v-if="this.date.day==5" for="">星期五</label>
              <label v-if="this.date.day==6" for="">星期六</label>
              <label v-if="this.date.day==7" for="">星期日</label>
  </div>
       
</template>
........//省略部分代码
data() {
    return {
      timer: null,//定时器
      date:{
        year:null,
        month:null,
        date:null,
        day:null,
        hours:null,
        minutes:null,
        seconds:null
      }
    };
  },
 
  mounted(){
    this.timer=setInterval(()=>{
          var now = new Date();
          this.date.year= now.getFullYear(); // 2015, 年份
          this.date.month=now.getMonth()+1; // 5, 月份,注意月份范围是0~11,5表示六月
          this.date.date=now.getDate(); // 24, 表示24号
          this.date.day=now.getDay(); // 3, 表示星期三
          this.date.hours=now.getHours(); // 19, 24小时制
          this.date.minutes=now.getMinutes(); // 49, 分钟
          this.date.seconds=now.getSeconds(); // 22, 秒
    },1000)

  },
  beforeDestroy(){
    if(this.timer){
      clearInterval(this.timer);
    }
  },
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值