有没有办法获得真实当前UTC时间戳,而不依赖于客户端在每个客户端上可能无法正确设置的时间?
我知道使用JavaScript getTime()
我可以获得UTC时间戳(以毫秒为单位)。它独立于客户的时区,但我认为它取决于客户当前的时间。
我试图制作一个显示实际UTC时间的实时时钟,因此如果客户端的时间设置正确或不正确,则无关紧要。
答案 0 :(得分:3)
获取此JSON:
http://json-time.appspot.com/time.json
或者
http://www.timeapi.org/utc/now
如果您有自己的服务器,也可以从自己的服务器上获取。
第一个例子(有间隔):
<强> HTML:强>
<div id="time">Click the button</div>
<button id="gettime">Get the time</button>
JAVASCRIPT(使用JQuery):
$("#gettime").click(function() {
setInterval(ajaxCalltoGetTime, 1000);
});
function ajaxCalltoGetTime() {
$.ajax({
type: "GET",
url: 'http://json-time.appspot.com/time.json',
dataType: 'jsonp'
})
.done(function( msg ) {
$("#time").html(msg.hour + ":" + msg.minute + ":" + msg.second );
});
JSFiddler: http://jsfiddle.net/op8xdsrv/
答案 1 :(得分:1)
您可以信任您的服务器时钟*。只需将当前UNIX时间戳从服务器发送到客户端即可。然后可以在JavaScript Date(value)
构造函数中使用。
<script>
var serverTime = new Date(<? php echo time(); ?> * 1000);
console.log(
serverTime.getUTCFullYear(),
serverTime.getUTCMonth() + 1,
serverTime.getUTCDate(),
serverTime.getUTCHours(),
serverTime.getUTCMinutes(),
serverTime.getUTCSeconds()
);
// use this time to seed your JavaScript clock
</script>
* 一般来说,服务器会定期将时间与时间提供商同步。
答案 2 :(得分:0)
您可以使用 timeanddate api 来获取日期和时间,而无需依赖客户端计算机或php中的服务器。然后将其发送到javascript。