Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying real time

I am currently displaying date/time on my webpage using the date function PHP provides. However, using this function, the date/time will only be updated when reloading the page. I wish to have the date/time updated every second instead.

I assume I have to use either javascript or jQuery/ajax for this, however I have no clue on how to do this. I was hoping anyone here could give me some advice.

Thanks in advance.

like image 841
Zilarion Avatar asked Apr 18 '11 14:04

Zilarion


3 Answers

Here's what I use (using jQuery)

var updateClock = function() {
    function pad(n) {
        return (n < 10) ? '0' + n : n;
    }

    var now = new Date();
    var s = pad(now.getUTCHours()) + ':' +
            pad(now.getUTCMinutes()) + ':' +
            pad(now.getUTCSeconds());

    $('#clock').html(s);

    var delay = 1000 - (now % 1000);
    setTimeout(updateClock, delay);
};

This is more accurate than just having a 1000ms timer since otherwise you get drift in the timings.

like image 120
Alnitak Avatar answered Nov 19 '22 15:11

Alnitak


I suget you to use the Date javascript oblect for display real time date/time

function Timer() {
   var dt=new Date()
   document.getElementById('time').innerHTML=dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds();
   setTimeout("Timer()",1000);
}
Timer();
like image 39
Yoann Avatar answered Nov 19 '22 16:11

Yoann


Are you looking to show the client's time or the server's time? You can look into javascript to have a running clock on your webpage, but it will just show the user's computer time. PHP will show the server's clock.

http://www.elated.com/res/File/articles/development/javascript/creating-a-javascript-clock/clock.html

Or the jQuery plugin: http://plugins.jquery.com/project/jqClock

like image 1
Aaron W. Avatar answered Nov 19 '22 16:11

Aaron W.