<script type="text/javascript">
/*
* 获得时间差,时间格式为 年-月-日 小时:分钟:秒 或者 年/月/日 小时:分钟:秒
* 其中,年月日为全格式,例如 : 2010-10-12 01:00:00
* 返回精度为:秒,分,小时,天
*/ function GetDateDiff(startTime, endTime, diffType) {
//将xxxx-xx-xx的时间格式,转换为 xxxx/xx/xx的格式
startTime = startTime.replace(/\-/g, "/");
endTime = endTime.replace(/\-/g, "/"); //将计算间隔类性字符转换为小写
diffType = diffType.toLowerCase();
var sTime = new Date(startTime); //开始时间
var eTime = new Date(endTime); //结束时间
//作为除数的数字
var divNum = 1;
switch (diffType) {
case "second":
divNum = 1000;
break;
case "minute":
divNum = 1000 * 60;
break;
case "hour":
divNum = 1000 * 3600;
break;
case "day":
divNum = 1000 * 3600 * 24;
break;
default:
break;
}
return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(divNum));
} var testDate = new Date();
var testStr = testDate.format("yyyy-MM-dd hh:mm:ss"); var result = GetDateDiff("2010-02-26 16:00:00", testStr, "day");
document.write("两者时间差为:" + result + "天了。");
</script>

jquery计算时间差(天、时、分、秒)并使用定时器实时获取

$(document).ready(function(){
run(enddate);
});
//定时器
function run(enddate){
//如果enddate为后台传入的Date类型,这里直接转化为毫秒数
enddate=new Date(eddate.replace("T"," ").getTime());
//以500毫秒的速度执行(可以避免方法执行速度慢会影响展示效果的情况)0
var time = 500;
setInterval("dateDif('"+enddate+"')",time);
}
//计算时间相差
function dateDif(enddate){
var date = enddate - new Date().getTime();
var days = date / 1000 / 60 / 60 / 24;
var daysRound = Math.floor(days);
var hours = date/ 1000 / 60 / 60 - (24 * daysRound);
var hoursRound = Math.floor(hours);
var minutes = date / 1000 /60 - (24 * 60 * daysRound) - (60 * hoursRound);
var minutesRound = Math.floor(minutes);
var seconds = date/ 1000 - (24 * 60 * 60 * daysRound) - (60 * 60 * hoursRound) - (60 * minutesRound);
var secondsRound = Math.floor(seconds);
var time = "倒计时"+(daysRound+"天"+hoursRound +"时"+minutesRound+"分"+secondsRound+"秒");
$("#ytime").text(time);
}
05-11 16:23
查看更多