如何使用 javascript 或 jquery 获取全球时间(不是电脑时间)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9862657/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:05:05  来源:igfitidea点击:

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

javascriptjquery

提问by Harshil Shah

I was creating a countdown timer using javascript; I can use jQuery. I want the global time not the PC time.

我正在使用 javascript 创建一个倒数计时器;我可以使用 jQuery。我想要全球时间而不是 PC 时间。

How could I get the global time using javascript or the jQuery?

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

回答by Ricardo Souza

Use a time API like: http://www.timeapi.org/

使用时间 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>

You can use the UTC methods from Dateobject: http://www.w3schools.com/jsref/jsref_obj_date.asp

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

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

回答by gilly3

The Dateobject has built-in methods for getting UTC values. Instead of myDate.getHours()use myDate.getUTCHours(), etc.

Date对象具有用于获取 UTC 值的内置方法。而不是myDate.getHours()usemyDate.getUTCHours()等。

See the MDN reference for JavaScript date methods.

请参阅 JavaScript日期方法的 MDN 参考。

回答by JP Silvashy

Well unless you make a request to some service that publishes like the current time of an atomic clock or something, you'll have to rely on your computers local time. As JS inherently relies on your local system.

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