//主方法 function xxx(){ //获取2个时间,一个是当前时间,一个是活动开始时间。然后传到getTimeOutMix方法中, //currentTime传过来的时候就是毫秒,startTimeStr时间是xxxx/hh/mm/ss 00:00:00格式 var timeOutMis = getTimeOutMis(currentTime,startTimeStr); var serverTimeArray = []; serverTimeArray.push(timeOutMis); countdown(serverTimeArray); } function getTimeOutMis(currentTime,startTimeStr) { var startTime = 0; if(startTimeStr != null || startTimeStr != '') { //把startTimeStr的格式转换为毫秒 startTime = Date.parse(new Date(startTimeStr)); } console.log(currentTime+ '==' + startTimeStr); console.log(currentTime+ '==' + startTime); var timeVal = startTime - currentTime; console.log(timeVal); return timeVal; } function countdown(time_distance) { //var $timer = $(".js_countdown"); // if ( $timer.size() < 0 || !isArray($timer)) { /* if ( $timer.size() < 0 || !isArray($timer)) { return; } */ var $timer = $(".js_countdown"); if ( $timer.size() < 0 || !isArray(time_distance)) { return; } $timer.each(function(e) { var time_arry = time_distance[e]; var me = $(this); main(time_arry,me); }); function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } function main(time_arry,elem) { if (time_arry >= 0) { var int_day, int_hour, int_minute, int_second; var timeDown = time_arry,timerID; //int_day = Math.floor(timeDown / 86400000); //timeDown -= int_day * 86400000; int_hour = Math.floor(timeDown / 3600000); timeDown -= int_hour * 3600000; int_minute = Math.floor(timeDown / 60000); timeDown -= int_minute * 60000; int_second = Math.floor(timeDown / 1000); //int_day = int_day < 10 ? "0" + int_day : int_day; int_hour = int_hour < 10 ? "0" + int_hour : int_hour; int_minute = int_minute < 10 ? "0" + int_minute : int_minute; int_second = int_second < 10 ? "0" + int_second : int_second; if(int_hour >=999) { int_hour = 999; } //把时,分,秒设置到页面class=count_hour,count_min,count_sec的元素上去 //elem.find(".day").text(int_day); elem.find(".count_hour").text(int_hour); elem.find(".count_min").text(int_minute); elem.find(".count_sec").text(int_second); //倒计时结束 重置计时器 if (parseInt(int_hour) == 0 && parseInt(int_minute) == 0 && parseInt(int_second) == 0) { clearTimeout(timerID); return; } time_arry -= 1000; timerID = setTimeout(function() { main(time_arry,elem); }, 1000); } else { clearTimeout(timerID); } } // main(); }
简单来说,过程是。计算2个时间的时间差。先把2个时间转换为毫秒,再相减。这个结果是倒计时的时间。
然后再把这个结果转换为日,时,分,秒,就好了
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/8701.html