如何使用javascript或jquery获取全局时间(而不是pc时间)

How to get global time(not the pc time) using javascript or jquery?

本文关键字:时间 pc 全局 javascript 何使用 jquery 获取      更新时间:2023-09-26

我使用javascript创建了一个倒计时计时器;我可以使用jQuery。我想要的是全球时间,而不是电脑时间。

如何使用javascript或jQuery获取全局时间?

使用时间API,如:http://www.timeapi.org/

<script type="text/javascript">
     function myCallback(json) {
          alert(new Date(json.dateString));
     }
</script>
<script type="text/javascript" src="http://timeapi.org/utc/now.json?callback=myCallback"></script>

您可以使用Date对象中的UTC方法:http://www.w3schools.com/jsref/jsref_obj_date.asp

var utcDate = new Date(json.dateString);
alert(utcDate.getUTCFullYear() + '-' + utcDate.getUTCMonth() + utcDAte.getUTCDate());

除非您向某个发布原子钟当前时间之类的服务发出请求,否则您将不得不依赖计算机的本地时间。由于JS本质上依赖于您的本地系统。

Date对象具有用于获取UTC值的内置方法。使用myDate.getUTCHours()等代替myDate.getHours()

有关JavaScript日期方法,请参阅MDN参考。

使用您当前的API服务器时间如下:

res.send(new Date());

您可以通过以下方式获得大致的时钟差时间:

// Get current local time before request
const initialLocalTime = new Date().getTime();
// Request server time
const response = await fetch('/api/time');
const data = await response.json();
const serverTime = new Date(data);
// Get current local time after request
const finalLocalTime = new Date().getTime();
// Calculate the request time
const dateDiff = finalLocalTime - initialLocalTime;
// Apply the request time to server time
serverTime.setTime(serverTime.getTime() + dateDiff);
// Calculate the time difference
const diff = serverTime.getTime() - finalLocalTime;
// Return the final difference time
return diff;

并且,您可以在页面中使用diff值:

const now = new Date()
now.setTime(now.getTime() + diff);
console.info('Current time:', now);