douzao9845 2013-11-08 22: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-08 22: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部