您的位置:首页 > Web前端 > JavaScript

js倒计时

2015-09-07 19:27 453 查看
//倒计时
function show_time() {
//正数表达式
var re = /^\d+(?=\.{0,1}\d+$|$)/;
var nd = 1000 * 24 * 60 * 60;
var nh = 1000 * 60 * 60;
var nm = 1000 * 60;
var ns = 1000;
var diff = jQuery("#orderCountDown").val();//到期时间
var now = format(new Date(), 'yyyy-MM-dd HH:mm:ss');//当前时间
//计算剩余的毫秒数
var myDiffTime = eval("new Date("+ diff.replace(/\D+/g,",")+")").getTime();
var myNowTime = eval("new Date("+ now.replace(/\D+/g,",")+")").getTime();
var ts = myDiffTime - myNowTime;
var dd = parseInt(ts / nd);//计算差多少天
var hh = parseInt(ts % nd / nh) + parseInt(+dd * 24);//计算差多少小时
var mm = parseInt(ts % nd % nh / nm);//计算差多少分钟
var ss = parseInt(ts % nd % nh % nm / ns);//计算差多少秒
dd = checkTime(dd);
hh = checkTime(hh);
mm = checkTime(mm);
ss = checkTime(ss);

if (re.test(ts)) {
// 显示时间
$(".time_d").text(dd);
$(".time_h").text(hh);
$(".time_m").text(mm);
$(".time_s").text(ss);
$(".time_ms").text(ts);

} else {
$(".time_h").text("00");
$(".time_m").text("00");
$(".time_s").text("00");
$(".time_ms").text("00");
}
// 设置定时器
setTimeout("show_time()", 1000);
};

function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
};

//将中国标准时间转化为指定格式时间
var format = function(time, format) {
var t = new Date(time);
var tf = function(i) {
return (i < 10 ? '0' : '') + i
};
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
switch (a) {
case 'yyyy':
return tf(t.getFullYear());
break;
case 'MM':
return tf(t.getMonth() + 1);
break;
case 'mm':
return tf(t.getMinutes());
break;
case 'dd':
return tf(t.getDate());
break;
case 'HH':
return tf(t.getHours());
break;
case 'ss':
return tf(t.getSeconds());
break;
}
})
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: