i have some difficulties showing the actual time of the server using php and js.
on the server-side i have following php code:
$date = new DateTime();
echo $date->getTimestamp();
on the client-side if have the following js code that changes the content of a div to display the current time:
flag = true;
timer = '';
function clock()
{
if ( flag ) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend/time_backend.php?action=serverTime", false);
xmlhttp.send();
var stamp = xmlhttp.responseText;
timer = stamp*1000;
}
var d = new Date(timer);
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
//hours = hours % 12;
//hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' + seconds;
document.getElementById("clock").innerHTML= strTime ;
flag = false;
timer = timer + 1000;
}
window.onload = function() {
setInterval(clock, 1000);
};
this works as long as the timezone of the server and mine are the same. but as soon as i change the timezone on the server, it doesn't work anymore. it still will show my local client time although the bash command date
on the server shows the time in the right offset.
how do i fix this? i really need to show the server-local time.
You are sending in unix timestamp from PHP must be probably using
if you want to use the string for creating date object using JS.
Your JS code should be
You could use an ISO 8601 formatted date.
Will give you one.
You could then do Date.parse() in which will return a timestamp ;) then proceed as if you received a timestamp.
Date::getTimestamp
always returns the Unix timestamp. Unix timestamp does not store time zone information.Solution is to build the JavaScript Date object from the date information given by the server.
Note: The time will not go out of sync when server or the client changes time zones (i.e. DST). If avoiding requests to backend a more accurate solution would be to use a time zone library in JavaScript (e.g. timezone.js).
PHP:
JavaScript: