douzao9845 2013-11-09 06:45 采纳率: 0%
浏览 52
已采纳

PHP:计算服务器和客户端之间的时差

I am building a chat for my website and I want to calculate the time difference between the server and the client. I am using the following code to get the time difference and put it in a hidden input field. But it doesn't work.

<script type = "text/javascript">
var time = new Date().getTime()/1000;
$.post('timediff.php',{time:time},function(response){
    alert(response);
});
</script>

And in my timediff.php file I have the following code:

<?php
if(isset($_POST['time'])){
    $client_time = $_POST['time'];
    $server_time = time();
    $time_diff = $server_time - $client_time;
    echo $time_diff;
}
?>

I tested this on another computer which has the same time setting as the server but the result that I am getting is larger. Am I doing anything wrong? Is there any better way to do this? Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongtang1910 2013-11-09 06:48
    关注

    Are you accounting for the latency between the client and the server? Even if they are one and the same, if it takes > 1 ms to process the response, you will get a non-zero difference.

    EDIT: Try getTimezoneOffset() (JavaScript, returns minutes) and DateTime::getOffset() (PHP, returns seconds). It's possible getTime() and time() are returning time-zone-dependent values. If you haven't set the timezone in your PHP script, that could also be a factor.

    You might also try this in your PHP:

    echo $client_time."
    ".$server_time;
    

    It could be useful to see what time JS and PHP are each reporting; it may be very different from the system time for any number of reasons.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题