如何使用javascript或jquery获取全局时间(而不是pc时间)
How to get global time(not the pc time) using javascript or jquery?
我使用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);
相关文章:
- Java脚本时间添加
- Json数据包含日期和时间格式
- 如何根据时间运行不同的脚本
- 用每小时的差值填充数组/列表-从下拉列表中给定两个时间值
- 在wordpress一定时间后更改自定义字段
- 更改angularjs中的日期-时间格式
- 将当前时间添加到我的页面上的特定部分
- 门户网站:当地时间有多有用
- 显示时间的脚本
- 如何在窗体打开时从javascript倒计时计时器值中节省时间
- 通过JSON&比较时间
- Javascript时间轨迹
- 引导日期选择器占用客户端PC时间,如何从服务器设置默认时间
- 在基于 PC 时间的 DIV 上添加类
- 如何使用javascript或jquery获取全局时间(而不是pc时间)
- 使用javascript获取PC时间并使用表单传递它
- 把pc's时间用在HTML表单上
- 从PC获取当前时间并保存在数据库中
- 在Javascript中测试PC时间是否正确
- 如何在Page_Load事件中获得客户端PC日期和时间