JavaScript距离当前日期倒计时的方法(Vue项目)

235 阅读1分钟

项目中,会遇到有过期时间的倒计时,使用方法如下:


export default {
		data() {
			return {
                day: 0, //天
		        hour: 0, //时
		        minute: 0,//分
		        second: 0,//秒
		        timer: null,
                expireat: '2022-05-01',//过期时间
			};
		},
        methods: {
          countDown(time) { //倒计时
		    const _this = this;
		    if (!time) {
			   return
		    }
		    let secondes = time;
		    this.timer = setInterval(() => {
			 let now = new Date().getTime();
			 if (now < secondes) {
				let diff = parseInt((secondes - now) / 1000); //相差多少秒
				let s = diff % 60; //秒
				let m = parseInt(diff / 60); //分钟
				let h = 0;//小时
				let d = 0; //天
				if (m > 60) {
					h = parseInt(m / 60);
					m = m % 60;
				}
				if (h > 24) {
					d = parseInt(h / 24);
					h = h % 24;
				}
				if (d >= 0) {
					d = d < 10 ? '0' + d : d
				}
				if (h >= 0) {
					h = h < 10 ? '0' + h : h
				}
				if (h >= 0 || m >= 0) {
					m = m < 10 ? '0' + m : m
				}
				s = s < 10 ? '0' + s : s,
                
                //时分秒赋值
			    this.day= d
				this.hour= h
				this.minute= m
				this.second= s
			} else {
				this.clearTimer()
			}
		}, 1000)
	},
	clearTimer() {
		clearInterval(this.timer);
		this.timer= null
	},
  },
  mounted() {
		let etimer = new Date(this.expireat).getTime(); //获取过期日期的时间戳
		this.countDown(etimer)	
  },
  destroyed() {
      this.clearTimer()      
  }
}

html显示:

<div>
    {{d}}天 {{h}}时 {{m}} 分{{s}}秒
</div>