Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript clock with server time PHP [duplicate]

I struggling with server time. I need timer on my website (count every second) but not client side time but server. But my script operating only with client time:

<script> 
setInterval(function() {
var d = new Date();
    $('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
}, 1000);
</script> 

<label id="timer"></label>

Script above work fine. How I can integrate server time and update very one second?

like image 727
Klapsius Avatar asked Feb 23 '26 00:02

Klapsius


1 Answers

Get the date from the server, convert it to a javascript date, then increment it yourself.

<?php $today = getdate(); ?>
<script>
    var d = new Date(Date.UTC(<?php echo $today['year'].",".$today['mon'].",".$today['mday'].",".$today['hours'].",".$today['minutes'].",".$today['seconds']; ?>));
    setInterval(function() {
        d.setSeconds(d.getSeconds() + 1);
        $('#timer').text((d.getHours() +':' + d.getMinutes() + ':' + d.getSeconds() ));
    }, 1000);
</script> 
<label id="timer"></label>

EDIT: JSFiddle with example PHP echoed in.

like image 162
James Hunt Avatar answered Feb 25 '26 12:02

James Hunt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!