距离某一天的倒计时我们只需要传递三个参数年月日即可返回
function counter(year,mouth,date) { div.innerHTML = `${innerHTMLs.slice(0,2)}${year}-${mouth}-${date}${innerHTMLs.slice(2)}`; let endDate = new Date(`${year}/${mouth}/${date}`); var t = Math.floor((endDate - newdate)/1000);//转换成秒 var seltime = setInterval(()=>{ --t; let time = {}; let day,h,f,s; if (t<=0){ clearInterval(seltime); day ='00', h = '00', f = '00', s = '00' }else { day =Optimize(Math.floor(t / ( 60 * 60 * 24))) ;//天数 h =Optimize(Math.floor((t % ( 60 * 60 * 24)) / (60 * 60))) ;//小时 f =Optimize(Math.floor((t % ( 60 * 60)) /60)) ;//分钟 s =Optimize(Math.floor(t %60)) ;//分钟 } time = {//最后返回的时间 day,h,f,s }; console.log(time) },1000); } function Optimize(v){ return v>=10?v:`0${v}` } counter('2020','5','20')//传三个参数 格式固定 '年','月','日'
距离第二天的倒计时
var nowDate = new Date();//获取到当前的时间 var newDate=new Date(nowDate.getFullYear(),nowDate.getMonth(), nowDate.getDate() + 1)//获取到第二天零点的时间 var t = Math.floor((newDate - nowDate)/1000);//转换成秒 var jdTimeInfo = document.querySelector('.kimsSecuritiesTime'); var jdTimeInfoSpan = jdTimeInfo.querySelectorAll('span'); var secKillTimer = null; secKillTimer = setInterval(function(){ t--; if(t < 0){ clearInterval(secKillTimer); return false; } var h = Math.floor(t%86400/3600); var m = Math.floor(t%3600/60); var s = Math.floor(t%60); var str = toTwo(h) + '时' + toTwo(m) + '分' + toTwo(s)+ '秒'; for(var i = 0; i < jdTimeInfoSpan.length; i++){ jdTimeInfoSpan[i].innerHTML = str.charAt(i); } }, 1000); function toTwo (n){ return n = n > 9 ? '' + n : '0' + n; }
根据后天返给的时间戳来判断(后天返回的一般为秒数)
var time = function (v) { var seltime = setInterval(()=>{ --v; let time = {}//设置一个对象 var t, h, f, s; if (v <= 0) { clearInterval(seltime); t = '00'; h = '00'; m = '00'; s = '00'; } else { this.liuyi = false; t = Optimize(Math.floor(v / (60 * 60 * 24)));//天数 h = Optimize(Math.floor((v % (60 * 60 * 24)) / (60 * 60)))//小时 f = Optimize(Math.floor(v % 3600 / 60));//分钟 s = Optimize(Math.floor(v % 60));//秒数 } time = {//最后返回的时间对象 t, h, f, s } console.log((time)) }, 1000) }; function Optimize(v){ return v>=10?v:`0${v}` } time(13123123)