js 倒计时-两个时间段倒计时

业务需求:分别在规定的两个时间段内进行 抢券倒计时
例如:时间一: 2020-01-16 00:00:00 开始抢券,2020-01-16 23:59:59 結束抢券
时间二: 2020-01-17 12::00:00 开始抢券 2020-01-17 23:59:59 結束抢券
html

<p class="time"></p>

Js

let clearFirstTime = null // 定时器
let curDay = new Date()// 当前时间
let hour = '00'
let minute = '00'
let second = '00'
let fristStartTime = '2020-01-16 00:00:00'// 第一次开始时间
let fristEndTime = '2020-01-16 23:59:59'// 第一次结束时间
let secondStartTime = '2020-01-17 12::00:00'// 第二次开始时间
let secondEndTime = '2020-01-17 23:59:59'// 第二次结束时间
clearFirstTime = setInterval(setStarTime, 1000)

function setStarTime() {
	let that = this
	let date = new Date()
	let now = date.getTime()
	let endDate = new Date(fristStartTime)
	let end = endDate.getTime()
	let leftTime = end - now
	let d = null
	let h = null
	let m = null
	let s = null
	// console.log(leftTime)
	if (leftTime >= 0) {
		d = Math.floor(leftTime / 1000 / 60 / 60 / 24)
		h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
		h = d * 24 + h
		m = Math.floor(leftTime / 1000 / 60 % 60)
		s = Math.floor(leftTime / 1000 % 60)
		hour = h < 10 ? '0' + h : h
		minute = m < 10 ? '0' + m : m
		second = s < 10 ? '0' + s : s
	} else {
		reducedTime()
		hour = '00'
		minute = '00'
		second = '00'
	}
	document.querySelectorAll('.time')[0].innerHTML = hour + '小时' + minute + '分' + second + '秒'
	// console.log(hour, minute, second)
}

function reducedTime() {
	let dayBlon = tab(curDay, fristEndTime)//  判断当前时间和第一次倒计时时间
	console.log(dayBlon)
	if (!dayBlon) {
		clearInterval(clearFirstTime)
		clearFirstTime = setInterval(setSecondTime, 1000)
	}
}

function tab(date1, date2) {
	var oDate1 = new Date(date1)
	var oDate2 = new Date(date2)
	// console.log('oDate1' + oDate1.getTime())
	// console.log('oDate2' + oDate2.getTime())
	if (oDate1.getTime() < oDate2.getTime()) {
		return true
	} else {
		return false
	}
}

function setSecondTime() {
	let that = this
	let date = new Date()
	let now = date.getTime()
	let endDate = new Date(secondStartTime)
	let end = endDate.getTime()
	let leftTime = end - now
	let d = null
	let h = null
	let m = null
	let s = null
	if (leftTime >= 0) {
		d = Math.floor(leftTime / 1000 / 60 / 60 / 24)
		h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
		h = d * 24 + h
		m = Math.floor(leftTime / 1000 / 60 % 60)
		s = Math.floor(leftTime / 1000 % 60)
		hour = h < 10 ? '0' + h : h
		minute = m < 10 ? '0' + m : m
		second = s < 10 ? '0' + s : s
	} else {
		clearInterval(clearFirstTime)
		hour = '00'
		minute = '00'
		second = '00'
	}
	document.querySelectorAll('.time')[0].innerHTML = hour + '小时' + minute + '分' + second + '秒'
}
发布了32 篇原创文章 · 获赞 1 · 访问量 5688
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览