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?
Visit the Web Page of the server you want to check. Select the entry and take a look at the HTTP Response Headers, you're looking for the one called 'Date' which contains the local time as well as the time zone of the server.
HTML <time> Tag.
Current Date and Time is stored inside javascript variable. Then using TextContent property the content of HTML span element is set with current and time. Unique ID is given to span tag so that we can use it on getElementById() method to dispaly the current date and time.
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>
The way I've gone about this before is:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With