html天时分秒倒计时,倒计时(天 时 分 秒)(原创)

//格式化时间

Date.prototype.format = function(format) {

/*

* 使用例子:format="yyyy-MM-dd hh:mm:ss";

*/

var o = {

"M+": this.getMonth() + 1, // month

"d+": this.getDate(), // day

"h+": this.getHours(), // hour

"m+": this.getMinutes(), // minute

"s+": this.getSeconds(), // second

"q+": Math.floor((this.getMonth() + 3) / 3), // quarter

"S": this.getMilliseconds() // millisecond

}

if (/(y+)/.test(format)) {

format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 -

RegExp.$1.length));

}

for (var k in o) {

if (new RegExp("(" + k + ")").test(format)) {

format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?

o[k] :

("00" + o[k]).substr(("" + o[k]).length));

}

}

return format;

}

$(function() {

function antitime() {

var time = "2019-10-31 23:59:59";

var to = new Date(time.replace(/-/g, "/"));

var now = new Date();

var deltaTime = to.getTime() - now.getTime();

//超时就停止倒计时

if (deltaTime <= 0) {

window.clearInterval(timer);

return;

}

var d = Math.floor(deltaTime / (1000 * 60 * 60 * 24));

//alert(PrefixInteger(d,2));

var h = Math.floor(deltaTime / 1000 / 60 / 60 % 24);

var m = Math.floor(deltaTime / 1000 / 60 % 60);

var s = Math.floor(deltaTime / 1000 % 60);

//把时间的数字转成字符串, 如果时分秒不足10, 则前面补0

var timeStr = "" + (d / 10 >= 1 ? d = d : d = "0" + d) + (h / 10 >= 1 ? h = h : h = "0" + h) + (m / 10 >= 1 ? m = m : m = "0" + m) + (s / 10 >= 1 ? s = s : s = "0" + s);

//console.log(timeStr);

//each循环遍历.num元素

$(".limited-time-sale .dingshi").each(function(index, span) {

$(span).html(timeStr.substring(index, index + 2));

if (index == 1) $(span).html(timeStr.substring(2, 4));

if (index == 2) $(span).html(timeStr.substring(4, 6));

if (index == 3) $(span).html(timeStr.substring(6, 8));

//$(span).html();这个方法是用来设置span里面的值的

});

}

//每秒执行一次

var timer = setInterval(antitime, 1000);

})

//时间补位(不够两位补零)

function PrefixInteger(num, length) {

return (Array(length).join('0') + num).slice(-length);

}

你可能感兴趣的:(html天时分秒倒计时)