ant*_*pug 7 javascript time datetime json
我需要使用 JSON 获取当前时间(从可靠来源)。精确时间在我的应用程序中至关重要,因此我不能依赖设备的时间,即使它只有一两秒钟。
编辑:我并不担心“精度”,而只是让运行该应用程序的多个设备具有相同的时间。
截至 2020 年 1 月 7 日,http://worldtimeapi.org/运行良好。我们可以以 json 格式或纯文本格式轻松获取特定时区或 IP 地址的当前日期和时间详细信息。
http://worldtimeapi.org/api/timezone/America/Santiago
Run Code Online (Sandbox Code Playgroud)
上述网址将为您提供“America/Santiago”的当前日期和时间详细信息(以 json 格式表示)。
http://worldtimeapi.org/api/timezone/Asia/Kolkata
Run Code Online (Sandbox Code Playgroud)
上述网址将为您提供“亚洲/加尔各答”的 json 格式的当前日期和时间详细信息。
根据您的公共 IP(JSON 格式)请求当前时间:
$ 卷曲“ http://worldtimeapi.org/api/ip ”
注意:默认情况下,API 返回 JSON。向任何 API URL 添加 .txt 后缀将返回纯文本响应,这在某些系统上可能更容易解析。
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
// This is where you do whatever you want with the time:
alert(time);
});
Run Code Online (Sandbox Code Playgroud)