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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀