简体   繁体   中英

How to display realtime change in server date and time every 1 Sec in php?

I wrote this php code to show server date and time but I'd like to display realtime change in server date and time every 1 Sec

<p><?php echo "Server Time " . date("Y-m-d h:i:s"); ?> (GMT) UTC +0 UK/London</p>

Pls help me, thank you

You will need to use Javascript, something like this:

<body>
<p id="time"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var timestamp = '<?=time();?>';
function updateTime(){
  $('#time').html(Date(timestamp));
  timestamp++;
}
$(function(){
  setInterval(updateTime, 1000);
});
</script>

if you still need a real time clock that uses your server clock you could try this. im using twig {{now|date('Y/m/d H:i:s')}} . but you could also use php's <?php echo date('Y/m/d H:i:s');?> . its basically using localStorage to store the server date on localstorage and setSeconds updates the localstorage every 1 second , while the now variable loads the localstorage date and converts it to js date format. I then use the {{now|date('Y/m/d H:i:s')}} inside the date element for fallback in case localstorage is not enabled.

  try {
localStorage.setItem('today', new Date("{{now|date('Y/m/d H:i:s')}}");
setInterval(function clock() {
    var month = [
    "Jan", "Feb", "Marh", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Octr", "Nov", "Dec"
    ];
    var now = new Date(localStorage.getItem('today'));
    now.setSeconds(now.getSeconds() + 1);
    localStorage.setItem('today', now);
    var G = format(now.getHours() % 12 || 12);
    var i = format(now.getMinutes());
    var s = format(now.getSeconds());
    var M = month[now.getMonth()];
    var d = format(now.getDate());
    var Y = now.getFullYear();
    function format(data) {
        return (data < 10 ? data = "0" + data : data);
    }
    $("#date").html(M + ". " + d + ", " + Y + " " + G + ":" + i + ":" + s);
    return clock;
}(), 1000);
} catch(e) {
    console.log(e);
}

you can get server time when page loaded and use javascript function to update time locally persecond. HTML PAGE

<script> var JS_BASE_URL = 'http://YOURSERVER/';</script>
<script src="assets/js/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="clock.js" type="text/javascript"></script>
</head>
<body>
Server Time  <span id="server_time">00:00:00</span>
</body>

clock.js

var url = JS_BASE_URL+'/script.php';
var _h = 0;
var _m = 0;
var _s = 0;
$.ajax({ 
    url: url,
    type: 'GET',
    dataType: 'JSON', 
    success: function(res) {
        var timer = setInterval(serverTime,1000);
        function serverTime(){
            h = parseInt(res.hour)+_h;
            m = parseInt(res.minute)+_m;
            s = parseInt(res.second)+_s;
            if (s>59){                  
                s=s-60;
                _s=_s-60;                   
            }
            if(s==59){
                _m++;   
            }
            if (m>59){
                m=m-60;
                _m=_m-60;                   
            }
            if(m==59&&s==59){
                _h++;   
            }   
            _s++;
            $('#server_time').html(append_zero(h)+':'+append_zero(m)+':'+append_zero(s));               }
        function append_zero(n){
            if(n<10){
                return '0'+n;
            }
            else
                return n;
        }
    }
});

script.php

<?php
$data = array('fulldate'=>date('d-m-Y H:i:s'),
              'date'=>date('d'),
              'month'=>date('m'),
              'year'=>date('Y'),
              'hour'=>date('H'),
              'minute'=>date('i'),
              'second'=>date('s')
        );
        echo json_encode($data);
?>

check on github: https://github.com/mdanielk/server_time

To display changing clock showing server time by using Ajax. Create two files for this one is the file sending request and receiving data with Ajax.

server-clock.php

develop a script where by clicking a button we can send a request to server to get the data. In the body of this file we have a button.

 <input type=button value=
'Get Server Time' onclick="timer_function();">  

To this script we will add a timer to recursively call the same Ajax function in every second. This will get data from every second so we can display a changing clock showing server time.

function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
}

Timer function: timer_function()

On click of this button it trigger a function which uses a timer setTimeout. Inside this timer function it can change the refresh rate which is in milliseconds. Within this function we call our main Ajax function AjaxFunction()

function timer_function(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('AjaxFunction();',refresh)
}

At the end of AjaxFunction() call again timer_function() to make it recursive.

tt=timer_function();

In the main AjaxFunction() send request to clock.php file and get the server time. This data is displayed using a div layer.

if(httpxml.readyState==4)
      {
document.getElementById("msg").innerHTML=httpxml.responseText;
document.getElementById("msg").style.background='#f1f1f1';
      }

The second file is the simple PHP file with one line of code giving current date and time of server. clock.php

<?Php
echo date("d/m/y : H:i:s", time());
?>

download the files here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM