Javascript clock with server time

Possible duplicate:
Create Live Clock javascript

I want to create a watch with javascript and php. It should start at server time (unix timestamp with php) and continue working with javascript. How to create it?

In this section, he said that he uses Date.now(); but this function returns a timestamp with milliseconds, and php does not return a millisecond.

Help me please.

Thanks.

+6
source share
4 answers

You will need to transfer the current server time to the page as it is created and use JavaScript to initialize your clock. Fortunately, the JS Date object will take a timestamp (in milliseconds) for initialization, so it's simple:

 <script type="text/javascript"> var d = new Date(<?php echo time() * 1000 ?>); </script> 

Pay attention to the part * 1000 . PHP timestamps are in seconds, and JS is in milliseconds.

+14
source

PHP has a miliseconds return function: http://php.net/manual/en/function.microtime.php

+2
source

I did it myself and posted it on github if this could be useful:

https://github.com/Lwangaman/jQuery-Clock-Plugin

It uses jquery, it is basically a jquery plugin, and a server timestamp may be required first. Css can also be easily modified according to your own preferences.

0
source

Could you just do it? Why does it take time from the server?

 <h4>It is now <script type="text/javascript"> <!-- var currentTime = new Date() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() if (minutes < 10){ minutes = "0" + minutes } document.write(hours + ":" + minutes + " ") if(hours > 11){ document.write("PM") } else { document.write("AM") } //--> </script> </h4> 
-1
source

Source: https://habr.com/ru/post/899381/


All Articles