开发者

Displaying real time

开发者 https://www.devze.com 2023-02-26 04:59 出处:网络
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 dat

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 wa开发者_开发问答s hoping anyone here could give me some advice.

Thanks in advance.


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.


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();


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


jquery ajax

setTimeout(function(){
    $.ajax({
      url: "server.php",
      type:"post",
      success: function(data){
       $('#showtime').html(data);

      }
    });
),1000});

server.php

update query //here you echo date/time in convenient format

html

<div id="showtime"></div>

ref http://api.jquery.com/jQuery.ajax/


You would need to use JavaScript/jQuery.

I wouldn't advise using Ajax and calls to the Webserver to load the time, as that would be an HTTP request every second for every user, which is a heck of a lot of traffic.

A tutorial for doing it in Javascript is here: http://www.elated.com/articles/creating-a-javascript-clock/

(Search Google for "Javascript" clock, there are many examples).


One way to do it which gives you the server time but without polling every second is to pass the timestamp to javascript (not the formatted time), then let javascript turn it into a formatted date and use setTimeout to add 1 second to the stamp, you just need to format the new timestamp each second. This gives you the server time but without expensive polling.

0

精彩评论

暂无评论...
验证码 换一张
取 消