<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>倒计时,美化版,去除最前面的0天,0小时等</title> <script> window.onload = function () { var _timer = null; var v = '2015-4-12 20:11:30'; go(v, 'timer'); } function go(v, id) { var date1 = new Date(); var data2 = new Date(v); _timer = setInterval(function () { if (data2 > date1) { leftTimer(data2, id) } else { document.getElementById(id).innerHTML = '已经结束';//设置的时间小于现在时间退出 window.clearInterval(_timer); _timer = null; } }, 1000); } function leftTimer(enddate, id) { var leftTime = (new Date(enddate)) - new Date(); //计算剩余的毫秒数 var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 var hours = parseInt(leftTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时 var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟 var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数 var d = days != 0 ? days + '天' : '';//当天数为0时,将00天移除,如不移除:days + '天' var h = days != 0 || days == 0 && hours != 0 ? toTwo(hours) + '小时' : '';//当天、小时都为0时移除00小时,如不移除:hours+'小时' var m = days != 0 || days == 0 && hours != 0 || days == 0 && hours == 0 && minutes > 0 ? toTwo(minutes) + '分' : '';//当天、时、分全为空时移除分。 var s = toTwo(seconds) + '秒'; if (days >= 0 || hours >= 0 || minutes >= 0 || seconds >= 0) document.getElementById(id).innerHTML = d + h + m + s; if (days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0) { document.getElementById(id).innerHTML= '已经结束'; window.clearInterval(_timer); _timer = null; } } function toTwo(n) { return n < 10 ? '0' + n : '' + n; } </script> </head> <body> <p id="timer"></p> </body> </html>
实例中