Recently I needed to add a clock to a page that showed the time according to the server and not the client’s machine. This was because the application runs a number of scheduled tasks that are set to run at specific times relative to the time on the server.
To do this I first needed to output the server time to a label on the page. With PHP you would do something like this:
<span id="serverClock"><?php echo date('h:i:s'); ?></span>
This gets the time based on the server’s clock and not the client machine and writes it out to a span on the page. The next step is to capture that time as text.
var serverClock = jQuery("#serverClock"); if (serverClock.length > 0) { showServerTime(serverClock, serverClock.text()); }
Here we are selecting the span containing the time and we’re then going to call a function called showServerTime. This function will accept two parameters; the first is the element that holds the time, the second is the time value.
var serverClock = jQuery("#serverClock"); if (serverClock.length > 0) { showServerTime(serverClock, serverClock.text()); } function showServerTime(obj, time) { var parts = time.split(":"), newTime = new Date(), timeDifference = new Date().getTime() - newTime.getTime(); newTime.setHours(parseInt(parts[0], 10)); newTime.setMinutes(parseInt(parts[1], 10)); newTime.setSeconds(parseInt(parts[2], 10)); var methods = { displayTime: function () { var now = new Date(new Date().getTime() - timeDifference); obj.text([ methods.leadZeros(now.getHours(), 2), methods.leadZeros(now.getMinutes(), 2), methods.leadZeros(now.getSeconds(), 2) ].join(":")); setTimeout(methods.displayTime, 500); }, leadZeros: function (time, width) { while (String(time).length < width) { time = "0" + time; } return time; } } methods.displayTime(); }
timeDifference = new Date().getTime() – newTime.getTime(); – Must go after setting params of new Time
newTime.setHours(), setMinutes and setSeconds should be called before setting timeDifference var.