PHP脚本-带时区的实时时钟

时间:2018-06-29 14:27:58

标签: php jquery html

我希望获得服务器时间的实时更新时钟。基本上是刷新日期(“ H:i:s T”);但是我无法正常工作。

应在以下位置进行更新:

<div id="clock"> </div>

我创建的函数如下:

<script>
function digitalClock() {
  var hrs;
  var mins;
  var tsecs;
  var secs;
  hrs = <?php echo date('H')?>;
  mins = <?php echo date('i')?>;
  secs = <?php echo date('s')?>;


  var ctime = hrs + ":" + mins + ":" + secs + " CEST";
  document.getElementById("clock").firstChild.nodeValue = ctime;
}
window.onload = function() {
  digitalClock();
  setInterval(digitalClock, 1000);
}
</script>

所以实际上它给出了正确的时间,但是根本没有更新。

如果有人能帮助我,我将非常感激。

如果有人可以解释我如何使用javascipt中的CEST时区来做到这一点,那就太棒了。

1 个答案:

答案 0 :(得分:0)

在您的情况下,小时,分钟和秒的值是固定的,因为PHP将显示它们一次,之后它们将成为常数,您需要做的是每次触发digitalClock()时刷新这些值,这是一种方法(您可以进一步编辑此代码以匹配您的时区/服务器时间),并希望它将对您有所帮助

<div id="clock"> </div>
    <script>
    function digitalClock() {
      var d = new Date();
      var h = d.getHours();
      var m = d.getMinutes();       
      var s = d.getSeconds();   
      var hrs;
      var mins;
      var tsecs;
      var secs;
      hrs = h;
      mins = m;
      secs = s;
      var ctime = hrs + ":" + mins + ":" + secs + " CEST";
      document.getElementById("clock").firstChild.nodeValue = ctime;
    }
    window.onload = function() {
      digitalClock();
      setInterval('digitalClock()', 1000);
    }
    </script>

您可以使用php获取所需的任何时区。

<?php

date_default_timezone_set("Europe/Berlin");
$tz_time = date("F j, Y h:i:s");

?>
<p id="clock"></p>

<script type="text/javascript">
                        var currenttime = '<?php echo $tz_time;?>'; // Timestamp of the timezone you want to use, in this case, it's server time
                        var servertime=new Date(currenttime);
                        function padlength(l){
                            var output=(l.toString().length==1)? "0"+l : l;
                            return output;
                        }
                        function digitalClock(){
                            servertime.setSeconds(servertime.getSeconds()+1);
                            var timestring=padlength(servertime.getHours())+":"+padlength(servertime.getMinutes())+":"+padlength(servertime.getSeconds());
                            document.getElementById("clock").innerHTML=timestring + " CEST";
                        }
                        window.onload=function(){
                        setInterval("digitalClock()", 1000);
                        }
</script>