用于显示服务器上的 javascript 时间的脚本不起作用

Script to show javascript time on server not working

本文关键字:时间 脚本 不起作用 javascript 用于 服务器 显示      更新时间:2023-09-26

我试图在我的页面上显示一个实时的javascript时钟,它显示了服务器上的时间。几周前,我在互联网上发现了这段代码,但它似乎并没有做它声称要做的事情。它显示客户端时间,而不是服务器时间。知道为什么吗?

flag = true;
timer = '';
setInterval(function(){phpJavascriptClock(<?php echo time(); ?>);},1000);

function phpJavascriptClock(timestamp)
{                 
  if ( flag ) {            
    timer = timestamp *  1000;
  }                     
  var d = new Date(timer);
  var currentDate = d.getDate();
  currentDate = currentDate < 10 ? '0'+currentDate : currentDate;
  var hours = d.getHours();    
  var minutes = d.getMinutes();
  var seconds = d.getSeconds();
  var ampm = hours >= 12 ? 'PM' : 'AM';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour ’0' should be ’12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  seconds = seconds < 10 ? '0'+seconds : seconds;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  var output = '';
  output += 
    '<a>'
    + '<i class="ace-icon fa fa-clock-o"></i>'
    + '<span class="">' + strTime + ' (SA)</span>'
    + '</a>'
  ;
  document.getElementById("current_time").innerHTML = output ;
  flag = false;
  timer = timer + 1000;
}

我看到这 4 个 Javascript DATE的构造函数:

new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds) 

可能是您的时间戳不millisecondsdateString,因此 Javascript 只是创建一个没有任何参数的新Date()对象(然后是客户端时间)?

编写一个新的基于 jQuery 的时钟。尽管它每分钟轮询一次服务器,但它可以工作。

我的控制器打发时间:

  public function getServerTimeAction() {
    global $config;
    try{
      $return["time"] = date("H:i a");
      $return["timezone"] = $config->application->timezone;
      $this->returnJson( JsonReturnObject::success( $return ) ) ;
    } catch ( Exception $e ) {
      $this->returnJson( JsonReturnObject::error( $e ) ); 
    }    
  }

jquery代码:

function getServerTime() {
  $.ajax({
    url : "{{ url('json/session/get-server-time') }}",
    cache : false,
    success : function ( data ) {
      if ( data.success ) {                             
        var output = '';
        output += 
          '<a>'
          + '<i class="ace-icon fa fa-clock-o"></i>'
          + '<span class="">' + data.data.time + ' (SA)</span>'
          + '</a>'
        ;
        $("#current_time").html(output);
        setTimeout(getServerTime, 60000);                         
      }                
    }
  })
}