首页 电脑 电脑学堂 查看内容

JavaScript倒计时获取服务器时间

2015-12-30 10:33 1971 0

摘要: 之前写过一篇:jQuery手机验证码倒计时效果,本文讲另外一种一个阶段的倒计时,这就需要用到服务器时间,毕竟本机时间可以人为的修改。//获取服务器时间 function getSevertime(){ var xmlHttp = new XMLHttpRequest ...
关键词: var 倒计时 xmlHttp 时间 html clockTime 本机 toString 服务器 floor

之前写过一篇:jQuery手机验证码倒计时效果,本文讲另外一种一个阶段的倒计时,这就需要用到服务器时间,毕竟本机时间可以人为的修改。

//获取服务器时间
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.常用获取服务器时间在倒计时应用中,例如以下,倒计时:

//换奖活动兑奖倒计时
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 += ''+d+'';
    if(h>=10) _html += ''+h.toString().slice(0,1)+''+h.toString().slice(1,2)+':';
    if(h<10) _html += '0'+h+':';
    if(m>=10) _html += ''+m.toString().substring(0,1)+''+m.toString().substring(1,2)+'';
    if(m<10) _html += '0'+m+'';
    if(getId('clockTime')){
        getId('clockTime').innerHTML = _html;
    }
}
setClock();//初始化
var clockTime = setInterval(setClock,60000);

显示效果如下:

原文链接:JavaScript倒计时获取服务器时间 版权所有,转载时请注明出处,违者必究。
注明出处格式:前端开发博客 (http://caibaojian.com/daojishi-2.html)
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系 [邮箱地址] 删除

路过
1

雷人

握手

鲜花

鸡蛋

刚表态过的朋友 (1 人)

  • 雷人

    匿名

最新评论

返回顶部