7

Possible Duplicate:
Making Live Clock javascript

I want to create a clock, with javascript and php. It should start from a server time (unix timestamp with php) and continue with javascript. How can I create it?

In this topic, he said to use Date.now();, but this function return a timestamp with milliseconds, and php doesn't return milliseconds.

Help me, please.

Thanks.

Community
  • 1
  • 1
mrdaliri
  • 7,148
  • 22
  • 73
  • 107
  • 2
    What do you get from php? If you get seconds, just multiply by 1000 and use `new Date()` – Tetaxa Oct 15 '11 at 21:33
  • 3
    We can help you code, not code for you. Please give it a try, and if you are stuck then come here with your exact, specific problem. Don't ask as us invent the wheel for you. – Madara's Ghost Oct 15 '11 at 21:33

4 Answers4

14

You'll have to pass the current server time into the page as it's created, and use that to initialize your javascript clock. Thankfully, JS's Date object will accept a timestamp (in milliseconds) to initalize with, so it's as simple as:

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

Note the * 1000 part. PHP's timestamps are in seconds, and JS's are in milliseconds.

Marc B
  • 356,200
  • 43
  • 426
  • 500
2

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

graywolf
  • 7,092
  • 7
  • 53
  • 77
0

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

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

It uses jquery, it's basically a jquery plugin, and it can take a server timestamp to start with. The css can also be easily modified to one's own likings.

JohnRDOrazio
  • 1,358
  • 2
  • 15
  • 28
-2

could you not just do this? Why does the time need to come 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>
Tules
  • 4,905
  • 2
  • 27
  • 29