首先看全部完整代码:
html部分代码:
可在文本框中输入倒计时的时间,如果当前时间小于截止时间,则正常返回,反之,则返回距离截止日期到现在的时间
javascript部分代码:
function countDown(endDate) {
var now = new Date();
var deadtime = document.getElementById(endDate);
var deadline = new Date(deadtime.value);
//本地时间与格林威治标准时间 (GMT) 的分钟差
var timeDiff = now.getTimezoneOffset();
//此处有些不解,如果把分钟差转化成毫秒应该是timeDiff*60*1000,但是这样返回的数据不正确!
var leave = Math.abs(deadline.getTime() - now.getTime() + timeDiff*60);
var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var countDay = Math.floor(leave/day);
//var countHour = Math.floor((leave - day*countDay)/hour); 两种计算思路
var countHour = Math.floor(leave/hour - countDay*24);
var countMinute = Math.floor(leave/minute) - countDay*24*60 - countHour*60;
var countSecond = Math.floor(leave/1000) - countDay*24*60*60 - countHour*60*60 - countMinute*60;
var outStr = "";
if(deadline outStr = "距离"+deadtime.value+"已有"+countDay+"天"+countHour+"小时"+countMinute+"分"+countSecond+"秒";
} else {
outStr = "距离"+deadtime.value+"还差"+countDay+"天"+countHour+"小时"+countMinute+"分"+countSecond+"秒";
}
var showTime = document.getElementById("showTime");
showTime.innerHTML = outStr;
}