How to get the real UTC timestamp (client independent)?

早过忘川 提交于 2019-12-12 16:03:28

问题


Is there a way to get the real current UTC timestamp without being dependent on the client's time which might not be set correctly on every client?

I know with JavaScript's getTime() I can get the UTC timestamp in milliseconds. It's independent of the client's timezone, but I think it's dependent of the client's current time.

I'm trying to make a live clock that shows the real UTC time, so it shouldn't matter if the client's time is set correctly or not for it to be correct.


回答1:


Get this JSON:

http://json-time.appspot.com/time.json

Or

http://www.timeapi.org/utc/now

Also you can get it from your own server if you have one.

For an example of the first one (with interval):

HTML:

<div id="time">Click the button</div>
<button id="gettime">Get the time</button>

JAVASCRIPT (With 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/




回答2:


You can trust your server's clock*. Just send the current UNIX timestamp from the server to the client. Then can use in JavaScript Date(value) constructor.

<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>

* Generally speaking, servers periodically synchronize their time with a time provider.




回答3:


you can use timeanddate api to get date and time without dependending on client machine or your server in php. Then send it to javascript.



来源:https://stackoverflow.com/questions/27019104/how-to-get-the-real-utc-timestamp-client-independent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!