Javascript 带有服务器时间的javascript时钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7780758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript clock with server time
提问by mrdaliri
Possible Duplicate:
Making Live Clock javascript
可能的重复:
制作实时时钟 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?
我想用 javascript 和 php 创建一个时钟。它应该从服务器时间(带有 php 的 unix 时间戳)开始,然后继续使用 javascript。我怎样才能创建它?
In this topic, he said to use Date.now();
, but this function return a timestamp with milliseconds, and php doesn't return milliseconds.
在这个话题中,他说使用Date.now();
,但是这个函数返回一个毫秒的时间戳,而php不返回毫秒。
Help me, please.
请帮帮我。
Thanks.
谢谢。
回答by Marc B
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:
您必须在创建页面时将当前服务器时间传递到页面中,并使用它来初始化您的 javascript 时钟。谢天谢地,JS 的 Date 对象将接受一个时间戳(以毫秒为单位)来初始化,所以它很简单:
<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.
注意* 1000
部分。PHP 的时间戳以秒为单位,JS 的时间戳以毫秒为单位。
回答by graywolf
PHP has function returning miliseconds: http://php.net/manual/en/function.microtime.php
PHP 有函数返回毫秒:http: //php.net/manual/en/function.microtime.php
回答by JohnRDOrazio
I did this myself and posted it on github if it can be useful:
我自己做了这个并将其发布在 github 上,如果它有用的话:
https://github.com/Lwangaman/jQuery-Clock-Plugin
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.
它使用 jquery,它基本上是一个 jquery 插件,它可以从服务器时间戳开始。css也可以根据自己的喜好轻松修改。
回答by Tules
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>