UTC clock based on server time?

I have a JavaScript clock that gets the time in UTC, it currently works, but the time is based off the client's computer. What could I do to base the time off of the server instead? I am using PHP as the server scripting language. I would like to not use AJAX.

<?php
$year   = date("Y");
$month  = date("m");
$day    = date("d");
$hour   = date("h");
$minute = date("i");
$str    = $year . $month . $day . $hour . $minute;
echo "history.pushState('', 'title', '?q=$str');";
echo "var ct = '$str';";
?>
function dT(){
    var d = new Date();
    d = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
    d.setTime(d.getTime());
    v = d.getFullYear() + "" +
            padstr(d.getMonth()) + "" +
            padstr(d.getDate()) + "" +
            padstr(d.getHours()) + "" +
            padstr(d.getMinutes()) + "" + padstr(d.getSeconds());
    if(ct !== v){
        history.pushState('', 'title', '?q=' + v);
        ct = v;
    }
    setTimeout('dT()', 1000);
}
dT();

Edit

    var a = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
    document.getElementById("time").innerHTML = a;
    function clock_tick(){
        var time = moment(a);
        time.add('second', 1);
        a = time.format("YYYY-MM-DD HH:MM:SS");
        document.getElementById("time").innerHTML = a;
        setTimeout("clock_tick()", 1000);
    }
    clock_tick();

Answers


This should get you started. You don't need to use moment.js, but I wanted to try it out since someone suggested it.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="moment.js"></script>
<script language="javascript">
$(function() {
    $('#clock')[0].innerHTML = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
    clock_tick();
});
function clock_tick(){
    var clock_div = $('#clock')[0];
    var time = moment(clock_div.innerHTML);
    time.add('second', 1);
    clock_div.innerHTML = time.format("YYYY-MM-DD hh:mm:ss");
    setTimeout("clock_tick()", 1000);
}
</script>
</head>
<body>
<div id="clock"></div>
</body>
</html>

Then as I stated earlier you may need to set:

date_default_timezone_set("UTC");

Reference Link: http://php.net/manual/en/function.date.php


Need Your Help

Options to display fields from different databases in WPF DataGrid?

wpf entity-framework

I am using .Net 4.0 framework, C#, WPF, EF 4 and FireBird.

Nhibernate dialect and driver to use for connecting to a sybase database in .net

c# nhibernate driver sybase dialect

In version 2 of Nhibernate, I had it working with below fluent nhibernate configuration: