JS根据服务器时间倒计时

时间:2022-02-27 17:05:55

原文链接:http://caibaojian.com/daojishi-2.html

//获取服务器时间
function getSevertime(){
var xmlHttp = new XMLHttpRequest();
if( !xmlHttp ){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("HEAD",location.href,false);
xmlHttp.send();
var severtime=new Date(xmlHttp.getResponseHeader("Date"));
return severtime;
}

其他的使用方式跟正常的使用JS一致,只是相比平时我们获取的是本机时间会比较准确和不会产生bug.常用获取服务器时间在倒计时应用中,例如以下,倒计时:

//code from http://caibaojian.com/daojishi-2.html
//换奖活动兑奖倒计时
var clockTime = null;
var clockRuning = false;
function setClock(){
    // var now = new Date();
    var now = getSevertime();
    var endTime = new Date('2016/01/16 10:00:00');
    var t = endTime.getTime() - now.getTime();
    if(t < 0) clearInterval(clockTime);
      var d=Math.floor(t/1000/60/60/24);
       var h=Math.floor(t/1000/60/60%24);
       var m=Math.floor(t/1000/60%60);
       var s=Math.floor(t/1000%60);
    var _html = '';
    if(d>0) _html += '<span class="muted">'+d+'</span><span class="span">天</span>';
    if(h>=10) _html += '<span class="muted">'+h.toString().slice(0,1)+'</span><span class="muted">'+h.toString().slice(1,2)+'</span><span class="span2">:</span>';
    if(h<10) _html += '<span class="muted">0</span><span class="muted">'+h+'</span><span class="span2">:</span>';
    if(m>=10) _html += '<span class="muted">'+m.toString().substring(0,1)+'</span><span class="muted">'+m.toString().substring(1,2)+'</span>';
    if(m<10) _html += '<span class="muted">0</span><span class="muted">'+m+'</span>';
    if(getId('clockTime')){
        getId('clockTime').innerHTML = _html;
    }
}