//将字符串格式化为时间
function parseDate(str) {
var bb = document.getElementById("bb");
if (typeof str == 'string') {
var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);
if (results && results.length > 3)
return new Date(parseInt(results[1], 10), parseInt(results[2], 10) - 1, parseInt(results[3], 10));
results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);
if (results && results.length > 6)
return new Date(parseInt(results[1], 10), (parseInt(results[2], 10) - 1), parseInt(results[3], 10), parseInt(results[4], 10), parseInt(results[5], 10), parseInt(results[6], 10));
results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);
if (results && results.length > 7)
return new Date(parseInt(results[1], 10), parseInt(results[2], 10) - 1, parseInt(results[3], 10), parseInt(results[4], 10), parseInt(results[5], 10), parseInt(results[6], 10), parseInt(results[7], 10));
}
return null;
}
//倒计时 deadline:截止日期,要求格式为:yyyy-MM-dd 或者 yyyy-MM-dd HH:mm:ss或者 yyyy-MM-dd HH:mm:ss.ms
// divname:倒计时要显示的位置
// type:1:显示精确到分;0:显示精确到秒
// msg1、msg2:当倒计时分别不为0、为0时显示的提示信息
function ShowCountDown(deadline, divname, type, msg1, msg2) {
var cc = document.getElementById(divname);
var now = new Date();
var endDate = parseDate(deadline);
if (endDate != null) {
var leftTime = endDate.getTime() - now.getTime();
if (leftTime > 0) {
var leftsecond = parseInt(leftTime / 1000);
var day = Math.floor(leftsecond / (60 * 60 * 24));
var hour = Math.floor((leftsecond - day * 24 * 60 * 60) / 3600);
var minute = Math.floor((leftsecond - day * 24 * 60 * 60 - hour * 3600) / 60);
var second = Math.floor(leftsecond - day * 24 * 60 * 60 - hour * 3600 - minute * 60);
if (cc != null) {
if (type == 1) {cc.innerHTML = msg1 + day + "天" + hour + "小时" + minute + "分";}
else { cc.innerHTML = msg1 + day + "天" + hour + "小时" + minute + "分" + second + "秒"; }
}
}
else {
cc.innerHTML = msg2;
}
}
}
使用例子:
var interval = 1000;
window.setInterval(function() { ShowCountDown('2010-6-11 15:36:00', 'div1', 1,'距停止报名还有 ', '活动已结束'); }, interval);