使用服务器和系统时间在网页上显示时钟?

发布于 2024-11-19 00:01:13 字数 122 浏览 2 评论 0原文

我需要向网页添加时钟。时钟需要与服务器同步,但我真的不想让它不断检查服务器,因为页面将在多台 PC 上 24/7 打开。有没有什么方法可以从服务器获取时间,然后使用系统时钟来保持更新,并每 15 分钟左右检查一次服务器以保持同步?

I need to add a clock to a web page. The clock needs to be synchronized with a server but I really don't want to have it constantly check the server as the page will be open 24/7 on several PCs. Is there some way to get the time from the server and then use the systems clock to keep it updated and check the server every 15 minutes or so to keep it synced?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

别再吹冷风 2024-11-26 00:01:13

我之前处理这个问题的方法是:

  • 从服务器获取时间,
  • 从客户端获取时间(立即)
  • 获取偏移量。
  • 显示时钟时,将偏移量应用到客户端上的当前时间。

您只需偶尔从服务器更新即可。

但您必须解决的问题是,在发出从服务器获取时间的请求时,在获取客户端时间之前会出现延迟。您可以通过使用 ajax 请求来获取服务器时间而不是其他任何东西来最大限度地减少这种情况,从而减少开销和网络延迟等。

The way I've gone about this before is:

  • Take the time from the server,
  • Take the time from the client (immediately)
  • Get an offset.
  • When showing the clock, apply the offset to the current time on the client.

You only need to update this occasionally from the server.

The problem that you've got to sort out though is that in making a request to get the time from the server, there will be a lag before you can get the client time. You can probably minimize this by using an ajax request to get the server time and nothing else, thereby cutting overhead and network lag etc.

牛↙奶布丁 2024-11-26 00:01:13

+Date.now() 返回自 Unix 纪元以来的本地毫秒数。因此:

  • 从服务器获取时间
  • 计算服务器时间和本地时间之间的差异
  • 通过获取本地时间并使用差异调整它,每秒或每分钟更新时钟(取决于您显示的内容)
  • 每 15 分钟更新一次差异。

或者类似的东西。

这是一个演示前半部分的小提琴

var serverTime = 1310127993162; //this would come from the server obviously
var localTime = +Date.now();
var timeDiff = serverTime - localTime;

setInterval(function () {
    console.log(+Date.now() + timeDiff);
}, 1000); 

+Date.now() returns local ms since the Unix epoch. So:

  • Get time from server
  • Calculate difference between server time and local time
  • Update the clock every second or minute (depending on what you're displaying) by getting the local time and adjusting it using the difference
  • Every 15 mins update the difference.

Or something like that.

Here's a fiddle demonstrating the first half:

var serverTime = 1310127993162; //this would come from the server obviously
var localTime = +Date.now();
var timeDiff = serverTime - localTime;

setInterval(function () {
    console.log(+Date.now() + timeDiff);
}, 1000); 
一身软味 2024-11-26 00:01:13
Server Time: <input type="text" id="clock" value="" size='8'>

<script type="text/javascript">
var serverTime = <?php echo time() * 1000; ?>; //this would come from the server
var localTime = +Date.now();
var timeDiff = serverTime - localTime;

setInterval(function () {
    var realtime = +Date.now() + timeDiff;
    var date = new Date(realtime);
    // hours part from the timestamp
    var hours = date.getHours();
    // minutes part from the timestamp
    var minutes = date.getMinutes();
    // seconds part from the timestamp
    var seconds = date.getSeconds();

    // will display time in 10:30:23 format
    var formattedTime = hours + ':' + minutes + ':' + seconds;

    $('#clock').attr('value',formattedTime); <-- input id=clock
}, 1000);
</script>
Server Time: <input type="text" id="clock" value="" size='8'>

<script type="text/javascript">
var serverTime = <?php echo time() * 1000; ?>; //this would come from the server
var localTime = +Date.now();
var timeDiff = serverTime - localTime;

setInterval(function () {
    var realtime = +Date.now() + timeDiff;
    var date = new Date(realtime);
    // hours part from the timestamp
    var hours = date.getHours();
    // minutes part from the timestamp
    var minutes = date.getMinutes();
    // seconds part from the timestamp
    var seconds = date.getSeconds();

    // will display time in 10:30:23 format
    var formattedTime = hours + ':' + minutes + ':' + seconds;

    $('#clock').attr('value',formattedTime); <-- input id=clock
}, 1000);
</script>
南风起 2024-11-26 00:01:13

一种想法是在请求时响应页面上的日期时间。
像:

<html>
your serveside codes,
<script>
var serverdatetime = new Date("<%=Datetime.Now%>");
//use serverdatetime and update it after 15 mins.

// you can use ajax to get datetime
setTimeout(function(){
    $.ajax({
  url: 'http://yourhost.com/getdate',
  success: function( data ) {
    // use data and update serverdatetime
  }
});},54000);
</script>
server codes

</html>

**注意:这只是想法,代码可能无法工作

one idea is to response datetime on page when it is requested.
like:

<html>
your serveside codes,
<script>
var serverdatetime = new Date("<%=Datetime.Now%>");
//use serverdatetime and update it after 15 mins.

// you can use ajax to get datetime
setTimeout(function(){
    $.ajax({
  url: 'http://yourhost.com/getdate',
  success: function( data ) {
    // use data and update serverdatetime
  }
});},54000);
</script>
server codes

</html>

**note : this is idea only, code may not work

紫竹語嫣☆ 2024-11-26 00:01:13

您可以在每次页面加载时从服务器获取当前时间,因此即使在第一次加载时您也将获得当前服务器时间。
之后,您可以在页面上使用 javascript 计时器,将其设置为每秒滴答一次,然后您实际上将拥有一个与服务器同步工作的时钟。您也可以尝试按照建议应用偏移量,但我不建议这样做,因为回发期间会出现延迟。

Ajax 请求可能是一个有趣的选择。

如有疑问,您还可以查看这个时钟!

另外,W3Schools 是 JavaScript 的一个很好的参考。

You can get the current time from the server on every page load, so even on first load you will have the current server time.
After that, you may use a javascript timer on the page set to tick every second, and then you will virtually have a clock working synchronized with the server. You may also try applying offsets as suggested, but i wouldn't recommend since there's lag during postbacks.

Ajax request might be an interesting option.

Any doubts, you may also check this clock out!

Also, W3Schools is a great reference for javascript.

终止放荡 2024-11-26 00:01:13
<script>
var ctoday = <?php echo time() * 1000 ?>;
setInterval(function() {ctoday += 1000;},1000);
function startTime() {
    var today = new Date(ctoday);
    var montharray = new Array("Jan","Feb","Mar","Abr","May","Jun","Jul","Ogu","Sep","Oct","Nov","Des");
    var h = today.getHours();
    var ampm = h >= 12 ? 'PM' : 'AM';
    h = h % 12;
    h = h ? h : 12;
    var m = today.getMinutes();
    var s = today.getSeconds();
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    checkTime(today.getDate())+" "+montharray[today.getMonth()]+" "+today.getFullYear() + " (" + ampm +" " + h + ":" + m + ":" + s +")"; 
    setTimeout(startTime, 1000);
}

function checkTime(i) {
    if (i < 10) {i = "0" + i};
    return i;
}
</script>
<body onLoad="startTime();">
    <span id="txt"></span>
</body>
  1. 使用 PHP 创建一个变量来保存服务器时间。
  2. 每 1 秒将 1000 添加到时间戳(1000 = 1 秒)。
  3. 现在获取营业时间。
  4. 现在实例化一个带有递增时间戳的新日期。
  5. 创建月份名称,
  6. 检测 AM 或 PM。
  7. 将小时格式从 24 转换为 12
  8. 获取分钟 获取
  9. 如果小时小于 10,则添加 0 条线索
  10. 如果分钟小于 10,则添加 0 条线索
  11. 如果秒小于 10,则添加 0 条线索
  12. 现在连接所有时间和日期并将它们放入 DOM 中元素
    ID为“txt”的
  13. 函数每1秒重复一次该函数
  14. ,函数加0以引导数字<; 10
<script>
var ctoday = <?php echo time() * 1000 ?>;
setInterval(function() {ctoday += 1000;},1000);
function startTime() {
    var today = new Date(ctoday);
    var montharray = new Array("Jan","Feb","Mar","Abr","May","Jun","Jul","Ogu","Sep","Oct","Nov","Des");
    var h = today.getHours();
    var ampm = h >= 12 ? 'PM' : 'AM';
    h = h % 12;
    h = h ? h : 12;
    var m = today.getMinutes();
    var s = today.getSeconds();
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =
    checkTime(today.getDate())+" "+montharray[today.getMonth()]+" "+today.getFullYear() + " (" + ampm +" " + h + ":" + m + ":" + s +")"; 
    setTimeout(startTime, 1000);
}

function checkTime(i) {
    if (i < 10) {i = "0" + i};
    return i;
}
</script>
<body onLoad="startTime();">
    <span id="txt"></span>
</body>
  1. Create a Variable holds server time using PHP.
  2. Adds 1000 to the time stamp every 1 sec (1000 = 1 sec).
  3. now get the Hours.
  4. Now instantiate a new date with incremented time stamp.
  5. creates a months names
  6. detect AM or PM.
  7. convert the hours format from 24 to 12
  8. Getting the minutes
  9. Getting the seconds
  10. add 0 leads if hours less than 10
  11. add 0 leads if minutes less than 10
  12. add 0 leads if seconds less than 10
  13. Now concatenate all time and date and put them in the DOM element
    with ID "txt"
  14. repeat the function every 1 sec
  15. function adds 0 to lead the numbers < 10
风吹过旳痕迹 2024-11-26 00:01:13

尝试下面的代码:

var m_serverDateTime;
var currentOffsetedTime;
var diffMilliseconds;

$(document).ready(function () {
   m_serverDateTime = getServerDateTime();/*your function to get server time 
by ajax call */   
diffMilliseconds = GetServerTimeDifference(m_serverDateTime);

});

 function GetServerTimeDifference(serverdatetime) {
  var fromdate = new Date();

  var todate = new Date(serverdatetime);

  var localdiffMilliseconds = todate - fromdate;

  return localdiffMilliseconds;
 }

setInterval(function () {
  //var currentOffsetedTime = new Date().setMinutes(diffMinutes);
  currentOffsetedTime = new Date();
  currentOffsetedTime.setMilliseconds(diffMilliseconds);

  $('#lblTimer').text(format(currentOffsetedTime, 'dd/MM/yyyy  HH:mm'));
}, 1000);

Try below code this :

var m_serverDateTime;
var currentOffsetedTime;
var diffMilliseconds;

$(document).ready(function () {
   m_serverDateTime = getServerDateTime();/*your function to get server time 
by ajax call */   
diffMilliseconds = GetServerTimeDifference(m_serverDateTime);

});

 function GetServerTimeDifference(serverdatetime) {
  var fromdate = new Date();

  var todate = new Date(serverdatetime);

  var localdiffMilliseconds = todate - fromdate;

  return localdiffMilliseconds;
 }

setInterval(function () {
  //var currentOffsetedTime = new Date().setMinutes(diffMinutes);
  currentOffsetedTime = new Date();
  currentOffsetedTime.setMilliseconds(diffMilliseconds);

  $('#lblTimer').text(format(currentOffsetedTime, 'dd/MM/yyyy  HH:mm'));
}, 1000);
南风起 2024-11-26 00:01:13

您只需从服务器获取一次日期时间,加载时调用此方法并使用 Moments js 来格式化日期:

var timeMiliSecond = new Date(serverTime).getTime();
 callRepeatedly() {
    setTimeout(() => {
         timeMiliSecond = timeMiliSecond+1000;         
         serverTime=moment(newDate(timeMiliSecond)).format('MM-DD-YYYY HH:mm:ss');
         this.callRepeatedly();
      }, 1000)  
  }

you just get one time date time from server, on load call this method and use moments js for format date:

var timeMiliSecond = new Date(serverTime).getTime();
 callRepeatedly() {
    setTimeout(() => {
         timeMiliSecond = timeMiliSecond+1000;         
         serverTime=moment(newDate(timeMiliSecond)).format('MM-DD-YYYY HH:mm:ss');
         this.callRepeatedly();
      }, 1000)  
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文