JS根据服务器时间倒计时

时间:2021-10-10 06:50:47

JS根据服务器时间倒计时

<!DOCTYPE html>
<html>
	<meta charset="utf-8" />
<head>  
<title>倒计时</title>  


<script type="text/javascript">  
/* 注意:需要放在服务端运行才能看到效果 */
get=function (id){return document.getElementById(id)}  
if(document.all){  
     window.XMLHttpRequest=function(){  
         var get=['Microsoft.XMLHTTP','Msxml2.XMLHTTP'];  
   for(var i=0;i<get.length;i++){try{return new ActiveXObject(get[i])}catch(e){}};  
     };  
}  
webDate=function(fn){  
  var Htime=new XMLHttpRequest();  
  Htime.onreadystatechange=function(){Htime.readyState==4&&(fn(new Date(Htime.getResponseHeader('Date'))))};  
  Htime.open('HEAD', '/?_='+(-new Date));  
  Htime.send(null);  
}  
//初始化 time  targetTime
window.time=null;   
targetTime=new Date();  
//时间格式化
time2String=function (t){  
   with(t)return [getFullYear(),'年'  
    ,('0'+(getMonth()+1)).slice(-2),'月'  
    ,('0'+getDate()).slice(-2),'日 '  
    ,('0'+getHours()).slice(-2),': '  
    ,('0'+getMinutes()).slice(-2),': '  
    ,('0'+getSeconds()).slice(-2)].join('')  
}  
//倒计时
int2time=function (m){  
  m-=(D=parseInt(m/86400000))*86400000;  
  m-=(H=parseInt(m/3600000))*3600000;  
  S=parseInt((m-=(M=parseInt(m/60000))*60000)/1000);  
  return D+'天'+H+'小时'+M+'分'+S+'秒'  
}  
//设置多少秒后重新获取服务器时间
/*setInterval(function (){  
	webDate(function (webTime){  
	//webTime.setSeconds(webTime.getSeconds()-2); //减一秒
	time=webTime;
  })  
},500000)  */
//服务器时间
webDate(function (webTime){  
	//webTime.setSeconds(webTime.getSeconds()-2); //减一秒
	time=webTime;
});  
//隔一秒刷新
setInterval(function (){  
	get('web').innerHTML=time2String(time); 
  	get('locale').innerHTML=time2String(new Date); 
	time.setSeconds(time.getSeconds()+1); //减一秒
  //时间对比 倒计时
  if(time==null){}
  else if(time.getFullYear()==1970){
  	get('time').innerHTML = '网络出错!';
  	return ;}
  else{
  	if ((targetTime-time)<0) {  
  		get('time').innerHTML = '结束';  
	}else{
	  get('time').innerHTML=int2time(targetTime-time);  
	}
  }
},1000)  
</script>   
</head>  
<body>  
设定时间      :<span id="locaTime">loading...</span><br />  
<!--设定时间+30:<span id="locaTime2">loading...</span><br />  -->
服务器时间:<span id='web'>loading...</span><br />  
本地时间:<span id="locale">loading...</span><br />  
倒计时时间:<span id="time">loading...</span>  
<script type="text/javascript" charset="utf-8">  

var endTime='2016-08-17 17:17:00';   //设置结束时间  初始化 
targetTime=new Date(endTime);
document.getElementById('locaTime').innerHTML=time2String(targetTime);
//targetTime.setMinutes(targetTime.getMinutes()+30);
//document.getElementById('locaTime2').innerHTML=time2String(targetTime);
</script>  
</body>  
</html>