通过js获取网站服务器时间

通过js获取网站服务器时间

谨慎使用,考虑不周有可能至使网站瘫痪。

 

 
 
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
  3. <head> 
  4. <meta http-equiv="Content-Type" content="text/html; charset=gbk"/> 
  5. <title>js获取服务器时间</title> 
  6. <script type="text/javascript"> 
  7.     get=function (id){return document.getElementById(id)} 
  8.     if(document.all){ 
  9.         window.XMLHttpRequest=function(){ 
  10.             var get=['Microsoft.XMLHTTP','Msxml2.XMLHTTP']; 
  11.             for(var i=0;i<get.length;i++){try{return new ActiveXObject(get[i])}catch(e){}}; 
  12.         }; 
  13.     } 
  14.     webDate=function(fn){ 
  15.         var Htime=new XMLHttpRequest(); 
  16.         Htime.onreadystatechange=function(){Htime.readyState==4&&(fn(new Date(Htime.getResponseHeader('Date'))))}; 
  17.         Htime.open('HEAD', '/?_='+(-new Date)); 
  18.         Htime.send(null); 
  19.     } 
  20.     window.time=new Date(); 
  21.     targetTime=new Date(); 
  22.     time2String=function (t){ 
  23.             with(t)return [getFullYear(),'年' 
  24.                 ,('0'+(getMonth()+1)).slice(-2),'月' 
  25.                 ,('0'+getDate()).slice(-2),'日 ' 
  26.                 ,('0'+getHours()).slice(-2),': ' 
  27.                 ,('0'+getMinutes()).slice(-2),': ' 
  28.                 ,('0'+getSeconds()).slice(-2)].join('') 
  29.     } 
  30.     int2time=function (m){ 
  31.         m-=(D=parseInt(m/86400000))*86400000; 
  32.         m-=(H=parseInt(m/3600000))*3600000; 
  33.         S=parseInt((m-=(M=parseInt(m/60000))*60000)/1000); 
  34.         return D+'天'+H+'小时'+M+'分'+S+'秒' 
  35.     } 
  36.     setInterval(function (){ 
  37.         webDate(function (webTime){ 
  38.             get('web').innerHTML=time2String(time=webTime); 
  39.         }) 
  40.         get('locale').innerHTML=time2String(new Date); 
  41.         get('time').innerHTML=int2time(targetTime-time); 
  42.         if ((targetTime-time)<0) { 
  43.             get('time').innerHTML = 'Game Over'
  44.         } 
  45.     },1000) 
  46.  </script>     
  47. </head> 
  48. <body> 
  49. 设定时间:2012年12月31日0时0分0秒<br> 
  50. 服务器时间:<span id='web'>loading...</span><br> 
  51. 本地时间:<span id="locale">loading...</span><br> 
  52. 倒计时时间:<span id="time">loading...</span> 
  53. <script type="text/javascript" charset="utf-8"> 
  54.     targetTime=new Date(2012,12,31,00,00,00); 
  55. </script> 
  56. </body> 
  57. </html> 

 

      本文转自许琴 51CTO博客,原文链接:http://blog.51cto.com/xuqin/882344,如需转载请自行联系原作者


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值