PHP: Calculate Time Difference Between your Users And Your Server

People access your site aren’t always in the same timezone as you are. Now perhaps you would like to determine what the time is for a user in a different country. Then here is a quick way to find this information out.

This example is very useful if you simply want to fetch your clients date and time or timezone; but also good to see what time of day (their time, not server time) your clients access your website.

Now before I should you the code, remember that PHP is server side code – ie. it runs on the server and as such doesn’t have access to the clients local time. Javascript however is client side code which means it can see the localtime but the servers time. So a combination of the two will allow us to calculate the difference.

The way the below example works, is that the client will click a submit button which sets the value of the hidden input field to their local time stamp and that gets submitted to the same php script. Then the php script checks if that value has been sent and if it has, then it gets the local time (of the server) and takes the clients times and shows a message depicting the difference.

[php toolbar=”true” classname=”one_line”] <!DOCTYPE html>
<title>Server and Client Time Example</title>
<script type=’text/javascript’>

// when we submit the form, get the client time and submit it as the
// hidden field ‘client_timestamp’
function getClientTime() {
var d = new Date();
// we divide the timestamp by 1000 to go from milliseconds to seconds
var timestamp = Math.floor(d.getTime()/1000);

// put the timestamp into hidden field to be passed with the form
document.getElementById(‘client_timestamp’).value = timestamp;


<form method=’post’ id=’myform’ onsubmit=’getClientTime();’>
<input type=’hidden’ id=’client_timestamp’ name=’client_timestamp’ />
<button type=’submit’>Send My Time</button>


// if the form with the timestamp was submitted
if( isset( $_REQUEST[‘client_timestamp’] ) ) {
// the time posted to this script through the form
$client_time = $_REQUEST[‘client_timestamp’];

$server_time = time();

$client_string = ‘Your clients time is: ‘;
$client_string .= date(‘d F Y h:i:s A’,$client_time);

$server_string = ‘Your server time is: ‘
$server_client .= date(‘d F Y h:i:s A’,$server_time);

// display the times
echo $client_string.'<br />’;
echo $server_string.'<br />’;




Leave A Comment