实际应用中,需要计算两个时间点之间的差,很多时候需要精确到天、小时、分钟和秒。
下面通过代码实例简单介绍一下如何实现此效果。
代码实例如下:
01020304050607080910111213141516171819202122232425262728293031323334353637383940414243<!DOCTYPE html>
<
html
>
<
head
>
<
meta
charset
=
" utf-8"
>
<
title
>计算时间差</
title
>
<
style
type
=
"text/css"
>
#ant{
font-size:2em;
}
</
style
>
<
script
type
=
"text/javascript"
>
function thenceThen() {
var theTime="2014/5/4"
var endTime=new Date(theTime);
var totalSecs=(endTime-new Date())/1000;
var days=Math.floor(totalSecs/3600/24);
var hours=Math.floor((totalSecs-days*24*3600)/3600);
var mins=Math.floor((totalSecs-days*24*3600-hours*3600)/60);
var secs=Math.floor((totalSecs-days*24*3600-hours*3600-mins*60));
if(days!=0) {
document.getElementById("ant").innerHTML=days+"天"+hours+"小时"+mins+"分钟"+secs+"秒";
}
else if(hours==0&&mins==0) {
document.getElementById("ant").innerHTML = secs + "秒";
}
else if(hours==0&&mins!= 0) {
document.getElementById("ant").innerHTML = mins + "分钟" + secs + "秒";
}
else if (hours!=0) {
document.getElementById("ant").innerHTML = hours + "小时" + mins + "分钟" + secs + "秒";
}
}
var clock;
window.onload=function() {
clock=setInterval("thenceThen()",500);
}
</
script
>
</
head
>
<
body
>
<
div
id
=
"ant"
></
div
>
</
body
>
</
html
>