js实现倒计时

首先,项目需求是需要根据当前时间实现截止于今天结束时间的倒计时,因此简单做一个倒计时的封装。

/**
	 * @param {Object} time 结束时间
	 * @param {Object} type 1 天时分秒 2 时分秒
	 */
	countDownTime(time, type) {
		var nowtime = new Date(), //获取当前时间
			endtime = new Date(time).getTime(); //定义结束时间
		let timestamp = endtime - nowtime.getTime(); //距离结束时间的毫秒数
		if (timestamp < 0) {
			return "截止了"
		}
		let D = Math.floor(timestamp / (1000 * 60 * 60 * 24)); //计算天数
		let H = Math.floor(timestamp / (1000 * 60 * 60) % 24); //计算小时数
		let m = Math.floor(timestamp / (1000 * 60) % 60); //计算分钟数
		let s = Math.floor(timestamp / 1000 % 60); //计算秒数
		if (H < 10) {
			H = '0' + H
		}
		if (m < 10) {
			m = '0' + m
		}
		if (s < 10) {
			s = '0' + s
		}
		if (type == 1) {
			return `${D}${H}小时${m}分钟${s}`
		} else {
			return `${H}小时${m}分钟${s}`
		}
	},
	/**
	 * @param {Object} time  时间
	 * @param {Object} type  0 年月日 1年月日时分秒
	 */
	formatterDate(date, type) {
		const time = date ? new Date(date) : new Date();
		const year = time.getFullYear() // 获取年
		const month = time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1 // 获取月
		const day = time.getDate() < 10 ? '0' + time.getDate() : time.getDate() // 获取日
		const hour = time.getHours() < 10 ? '0' + time.getHours() : time.getHours() // 获取小时
		const minute = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes() // 获取分钟
		const second = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds() // 获取秒
		if (type == 0) {
			return year + '-' + month + '-' + day
		} else {
			return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
		}
	},

封装的js代码如上,接下来是调用示例

mounted() {
	// 进入页面调用
	this.realTime()
},
beforeDestroy() {
	clearInterval(this.timer); // 清除定时器
	this.timer = null;
},
methods: {
	realTime() {
		this.timer = setInterval(() => {
			// 获取当前时间的截止时间
			const endTime = this.$utils.formatterDate('', 0) + ' 23:59:59'
			this.downTime = this.$utils.countDownTime(endTime)
		}, 1000)
	}
}

在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值