簡體   English   中英

使用服務器和系統時間在網頁上計時?

[英]Clock on webpage using server and system time?

我需要向 web 頁面添加時鍾。 時鍾需要與服務器同步,但我真的不想讓它不斷檢查服務器,因為該頁面將在多台 PC 上 24/7 全天候打開。 有沒有辦法從服務器獲取時間,然后使用系統時鍾來保持更新並每 15 分鍾左右檢查一次服務器以保持同步?

我以前解決這個問題的方法是:

  • 從服務器上花時間,
  • 從客戶那里抽出時間(立即)
  • 得到一個偏移量。
  • 顯示時鍾時,將偏移量應用於客戶端的當前時間。

您只需要偶爾從服務器更新它。

但是,您必須解決的問題是,在發出從服務器獲取時間的請求時,在獲取客戶端時間之前會有延遲。 您可能可以通過使用 ajax 請求來獲取服務器時間而不是其他任何東西來最小化這種情況,從而減少開銷和網絡延遲等。

+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); 
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>

一種想法是在請求時響應頁面上的日期時間。 喜歡:

<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>

**注意:這只是想法,代碼可能不起作用

<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 = 1 秒)將 1000 添加到時間戳。
  3. 現在得到小時。
  4. 現在實例化一個帶有遞增時間戳的新日期。
  5. 創建月份名稱
  6. 檢測上午或下午。
  7. 將小時格式從 24 轉換為 12
  8. 獲取會議記錄
  9. 獲得秒數
  10. 如果小時數少於 10,則添加 0 個潛在客戶
  11. 如果分鍾小於 10,則添加 0 個潛在客戶
  12. 如果秒數小於 10,則添加 0 個潛在客戶
  13. 現在連接所有時間和日期,並將它們放入 ID 為“txt”的 DOM 元素中
  14. 每 1 秒重復一次 function
  15. function 加 0 前導數字 < 10

試試下面的代碼:

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);

您只需從服務器獲取一個時間日期時間,在加載時調用此方法並使用時刻 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)  
  }

您可以在每次頁面加載時從服務器獲取當前時間,因此即使在第一次加載時,您也將擁有當前服務器時間。 之后,您可以在設置為每秒計時的頁面上使用 javascript 計時器,然后您實際上將擁有一個與服務器同步的時鍾。 您也可以嘗試按照建議應用偏移量,但我不建議這樣做,因為回發期間存在滯后。

Ajax 請求可能是一個有趣的選項。

有任何疑問,您也可以查看這個時鍾!

此外, W3Schools是 javascript 的一個很好的參考。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM