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.
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.