格式化将0-9变成00-09的显示方式
function forNum(num) { if (num < 10) return "0" + num; else return num; }
countdown函数计算时间差返回数组形式,数组的第一个返回字符串,第二个返回布尔值判断是否结束
参数:d1是服务器端传过来的秒形式
d2是时间的字符串
function countdown(d1, d2) { var endTime = new Date(d2).getTime() / 1000; var d = endTime - d1; var second = parseInt(d % 60); var minite = parseInt((d / 60) % 60); var hour = parseInt((d / 3600) % 24); var day = parseInt(d / 3600 / 24); var b = true; var timeArray = [second.toString(), minite.toString(), hour.toString()]; if (d <= 0) { return ["00小时00分00秒", true]; } else { if (day > 0) { return [day + "天" + forNum(timeArray[2]) + "小时" + forNum(timeArray[1]) + "分" + forNum(timeArray[0]) + "秒", false]; } else { return [forNum(timeArray[2]) + "小时" + forNum(timeArray[1]) + "分" + forNum(timeArray[0]) + "秒", false]; } } }
倒计时:
<!DOCTYPE html> <html> <head> <title>倒计时</title> </head> <body> <div id="test"></div> <script type="text/javascript"> function forNum(num) { if (num < 10) return "0" + num; else return num; } function countdown(d1, d2) { var endTime = new Date(d2).getTime() / 1000; var d = endTime - d1; var second = parseInt(d % 60); var minite = parseInt((d / 60) % 60); var hour = parseInt((d / 3600) % 24); var day = parseInt(d / 3600 / 24); var b = true; var timeArray = [second.toString(), minite.toString(), hour.toString()]; if (d <= 0) { return ["00小时00分00秒", true]; } else { if (day > 0) { return [day + "天" + forNum(timeArray[2]) + "小时" + forNum(timeArray[1]) + "分" + forNum(timeArray[0]) + "秒", false]; } else { return [forNum(timeArray[2]) + "小时" + forNum(timeArray[1]) + "分" + forNum(timeArray[0]) + "秒", false]; } } } var startTime = 1340899199; var stop = setInterval(function () { var arr = countdown(startTime, "6/29/2012 23:59:59"); if (arr[1]) { clearInterval(stop); } else { startTime++; } document.getElementById("test").innerHTML = arr[0]; }, 1000); </script> </body> </html>