Displaying timer from server time instead of using client side time in Javascript

Here is the useful Javascript function, which retrieves the Server Date Time from PHP and stores into Javascript variable. Finally runs the timer in Javascript.

<script type="text/javascript">
var currenttime = '<? echo date("F d, Y H:i:s", time())?>' //PHP method of getting server date
///////////Stop editting here/////////////////////////////////
var montharray= new Array("January","February","March","April","May","June", "July","August","September","October","November","December");
var serverdate=new Date(currenttime);
function padlength(what){
	var output=(what.toString().length==1)? "0"+what : what;
	return output;
function displaytime(){
	var datestring=montharray[serverdate.getMonth()]+" "+padlength(serverdate.getDate())+", "+serverdate.getFullYear();
	var timestring = padlength(serverdate.getHours())+":"+padlength(serverdate.getMinutes())+ ":" + padlength(serverdate.getSeconds());
	document.getElementById("clock").innerHTML = datestring + " " + timestring;
setInterval("displaytime()", 1000);

2 thoughts on “Displaying timer from server time instead of using client side time in Javascript

  1. I like reading websites like these. It has been an nice source of info. I could not locate sites like these. Thanks once again.

  2. I have been looking for a PHP/Javascript code for a running clock for weeks. Now I can display the local time correctly in my Opencart Shopping Cart.
    Simple, configurable and powerful, just what I was after!
    Thank you for providing it.

Leave a Reply

Your email address will not be published. Required fields are marked *