Clock on webpage using server and system time?

痴心易碎 提交于 2019-11-30 12:01:56

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.

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

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

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>

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.

<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

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

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)  
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!