简体   繁体   English

如何在php中每1秒显示服务器日期和时间的实时变化?

[英]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我写了这个 php 代码来显示服务器日期和时间,但我想每 1 秒显示一次服务器日期和时间的实时变化

<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:您将需要使用 Javascript,如下所示:

<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')}} .我正在使用树枝{{now|date('Y/m/d H:i:s')}} but you could also use php's <?php echo date('Y/m/d H:i:s');?> .但你也可以使用 php 的<?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.它基本上使用localStorage将服务器日期存储在localstoragesetSeconds每 1 秒更新一次localstorage ,而 now 变量加载localstorage日期并将其转换为 js 日期格式。 I then use the {{now|date('Y/m/d H:i:s')}} inside the date element for fallback in case localstorage is not enabled.然后,我在date元素中使用{{now|date('Y/m/d H:i:s')}}进行回退,以防未启用 localstorage。

  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.您可以在页面加载时获取服务器时间,并使用 javascript 函数在本地每秒更新时间。 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时钟.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检查github: https : //github.com/mdanielk/server_time

To display changing clock showing server time by using Ajax.使用 Ajax 显示显示服务器时间的更改时钟。 Create two files for this one is the file sending request and receiving data with Ajax.为此创建两个文件,分别是用 Ajax 发送请求和接收数据的文件。

server-clock.php服务器时钟.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.在这个脚本中,我们将添加一个计时器,以每秒递归调用相同的 Ajax 函数。 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()定时器函数:timer_function()

On click of this button it trigger a function which uses a timer setTimeout.单击此按钮时,它会触发一个使用计时器 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()在这个函数中,我们调用我们的主要 Ajax 函数 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.在 AjaxFunction() 结束时再次调用 timer_function() 使其递归。

tt=timer_function();

In the main AjaxFunction() send request to clock.php file and get the server time.在主 AjaxFunction() 中发送请求到 clock.php 文件并获取服务器时间。 This data is displayed using a div layer.此数据使用 div 层显示。

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.第二个文件是简单的 PHP 文件,其中一行代码给出了服务器的当前日期和时间。 clock.php时钟.php

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

download the files here这里下载文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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