js获取服务器时间

稿件来源: 阳光企业网站管理系统   撰稿作者: 太阳光   发表日期: 2011-04-13   阅读次数: 597   查看权限: 游客查看

js属于客户端代码,一般获取的时间都是客户端时间。有些时候我们必须获取客户端的时间。

 

<script>
//===js获取服务器时间
if(document.all){
    window.XMLHttpRequest=function(){
        var $=['Microsoft.XMLHTTP','Msxml2.XMLHTTP'];
	for(var i=0;i<$.length;i++){try{return new ActiveXObject($[i])}catch(e){}};
    };
}
function webDate(fn){
       var QQ=new XMLHttpRequest();
       QQ.onreadystatechange=function(){QQ.readyState==4&&(fn(new Date(QQ.getResponseHeader('Date'))))};
       QQ.open('HEAD', '/?_='+(-new Date));
       QQ.send(null);
}
function time_str(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('')
}

webDate(function (webTime){
var web_time=time_str(webTime);
alert(web_time);
})
</script>

今天无意间看到另一种方法,我觉得这种方法更好,不用频繁发送ajax
 

<html>
<head>
<script>
function RunTime(o){
    var TimeDifference = new Date() - new Date(o.innerText.replace(/-/g,"/"));
		alert(TimeDifference);
    (function ()
    {
        var d = new Date();
        d.setTime(d.getTime()+TimeDifference);
        o.innerText = d.toLocaleString();
        setTimeout(arguments.callee,1000);
    })();
}
</script>
</head>
<body onload="RunTime(document.getElementById('oTime'));">服务器时间:<span id="oTime"><%=now%></span>
</body>
</html> 

关键词: 服务器时间,javascript   编辑时间: 2011-05-18

  • 感到高兴

    0

    高兴
  • 感到支持

    0

    支持
  • 感到搞笑

    0

    搞笑
  • 感到不解

    0

    不解
  • 感到谎言

    0

    谎言
  • 感到枪稿

    0

    枪稿
  • 感到震惊

    0

    震惊
  • 感到无奈

    0

    无奈
  • 感到无聊

    0

    无聊
  • 感到反对

    0

    反对
  • 感到愤怒

    0

    愤怒
0%(0)
100%(2)
共有0 条评论 发言请遵守【相关规定

网友评论

会员头像
发 表同步腾讯微博    验证码:  点击更新请先登陆
  • 暂无评论
关闭模块文章图片 article Pictrue
  • 我的妈妈爸爸
  • 基于koa2+mysql+vue2.0+Element阳光内容管理系统
  • 代码覆盖率工具 Istanbul 入门教程
  • 全栈工程师的武器——MEAN
  • 9款超炫的 CSS3 复选框(Checkbox)
  • 微信开发在线翻译功能
  • CSS3那些不为人知的高级属性
  • 给easyui的datebox添加清空事件
  • flash写字效果
  • kendoUI系列教程之DropDownList下拉菜单
  • kendoUI系列教程之datetimepicker日期时间选择
  • kendoUI系列教程之datepicker日期选择
  • kendoUI系列教程之combobox下拉列表框
  • kendoUI系列教程之colorpicker
  • kendoUI系列教程之calendar日历表
  • kendoUI系列教程之autocomplete自动补齐