How to display server time in JavaScript

Sometimes you must display server name in real time. This time may be different that the one user sees on it's device.

For this example you need PHP, JS and jQuery.

Lets start with displaying current server time

Current server time is  

As you can see I am only wrapping time part because date part is not interesting for me. With little code adjustments you can include date part too.

Now time to start processing our output

    var timeField = $('#server-time');
    showServerTime(timeField, timeField.text());

Here we select our time element and send him and it's content to function below. Also you can pass different time for that function.

function showServerTime(obj, time) {
    var parts = time.split(":");
    var newTime = new Date();
    newTime.setHours(parseInt(parts[0], 10));
    newTime.setMinutes(parseInt(parts[1], 10));
    newTime.setSeconds(parseInt(parts[2], 10));

    var timeDifference = new Date().getTime() - newTime.getTime();
    var methods = {
        displayTime: function () {
            var now = new Date(new Date().getTime() - timeDifference);
            setTimeout(methods.displayTime, 1000);
        leadZeros: function (time) {
            while (String(time).length < 2) {
                time = "0" + time;

            return time;


In this function we are using JavaScript Date() class to maipulate time expressions.

This function will automatically call itself every second and updates passed element. Also it will fix missing leading zeros issue where instead of 2015-09-05 01:06:08 you will get 2015-9-5 1:6:8.

Replaying to
Leave comment
server time | Reply Cancel
why, fuck, you need fucking jquery for something like that... die jquery