dongyi5425 2013-09-04 09:58
浏览 30
已采纳

创建与区域相关的时钟

I have a working clock for my local server and for my browser (local system). Both works great. Now what I want to do is find the time offset between the clocks, based on seconds, and add it to the local system clock.

For example: my system clock is: 10:00:00 and the server clock is 12:15:00 at the same date. then the offset will be: 02:15:00 (of course it will be in seconds but just for the example I wrote it that way). And then add it to (browser)local time so I eventually get to show the server time. 12:15:00.

This is what I'm doing here:

var interval = self.setInterval(function(){
  clock();
},1000);

function clock()
{   
    //Get local server time
    <?php $today = getdate(); ?>;
    var ser = <?php echo $today[0]; ?>;

    //Local client time
    var seconds = Date.now();
    var offset = seconds-ser*1000;
    parseInt(offset/1000);

    var d = new Date();
    d.setTime(Date.now()-offset);
    var h = d.getHours();
    var m = d.getMinutes();
    var s = d.getSeconds();

    if(s < 10)
      s = "0" + s;
    if(m < 10)
      m = "0" + m;
    if(h < 10)
      h = "0" + h;

    var tm = h+":"+m+":"+s;
    document.getElementById("clock").value = tm;
} 

But as soon as I put the variable

offset

in this line: d.setTime(Date.now()-offset);

The clock doesn't updates anymore. I guess there is an issue with PHP compatibility. Any idea how to solve it? Thanks

  • 写回答

2条回答 默认 最新

  • du20150401 2013-09-04 10:38
    关注

    The offset calculation has to be outside of the repeadly called function:

    //Get local server time
    <?php $today = getdate(); ?>;
    var ser = <?php echo $today[0]; ?>;
    
    //Local client time
    var seconds = Date.now();
    var offset = seconds-ser*1000;
    parseInt(offset/1000); // BY THE WAY: As the returnval of parseInt isn't stored anywhere, this line does nothing
    
    var interval = self.setInterval(function(){
      clock();
    },1000);
    
    function clock()
    {   
    
        var d = new Date();
        d.setTime(Date.now()-offset);
        var h = d.getHours();
        var m = d.getMinutes();
        var s = d.getSeconds();
    
        if(s < 10)
          s = "0" + s;
        if(m < 10)
          m = "0" + m;
        if(h < 10)
          h = "0" + h;
    
        var tm = h+":"+m+":"+s;
        document.getElementById("clock").value = tm;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。