如何在特定时区使用moment.JS并实时显示 [英] How to use moment.JS for a certain timezone and display it in real time

查看:219
本文介绍了如何在特定时区使用moment.JS并实时显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Moment.JS库用于国际时区并实时显示?

How do I go about using the Moment.JS library for an international timezone and display it in real time?

这是我目前在索引中所拥有的页面。

This is what I have so far in my index page.

代码:

Code:

<!DOCTYPE html>
<html>
<head>
<script src="moment.js"></script>
<script src="moment-timezone.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
    moment().tz("America/Los_Angeles").format();
    document.getElementById("time").firstChild.data = moment().format('hh:mm:ss a')
</script>
</head>
<body>
    <span id="time">s</span>
</body>
</html>

这是我第一次使用MomentJS,我不知道我是否已正确实现并显示它实时不经常刷新页面。

This is my first time using MomentJS and I dont know if I have implemented it correctly and to display it in real time without refreshing the page constantly.

推荐答案

您缺少实际的区域数据。转到时刻 - 时区数据构建器并包含您关注的区域。将它放在另一个名为 moment-timezone-data.js 的文件中并包含它,或者将其放入现有脚本中。请参阅这些文档

You are missing the actual zone data. Go to the moment-timezone data builder and include the zones you care about. Put that in another file called moment-timezone-data.js and include it, or place it inline your existing script. See these docs.

要实时更新它,您需要定期更新元素。

To update it in realtime, you need to update the element on a regular interval.

此外,在您的示例代码中,您第一次调用时与时区的关系,你扔掉了回应。第二个电话,你没有使用时区。而你在这里不需要jQuery。

Also, in your example code, the first time you are calling moment with the timezone, you are throwing away the response. The second call, you're not using the time zone. And you don't need jQuery here.

全部放在一起:

function showTheTime() {
    var s = moment().tz("America/Los_Angeles").format('hh:mm:ss a');    
    document.getElementById("time").innerHTML = s;
}

showTheTime(); // for the first load
setInterval(showTheTime, 250); // update it periodically

您可能认为将间隔设置为1000毫秒就可以,但是你可能会发现它在视觉上不能顺利打勾。发生这种情况是因为间隔计时器可能与实际时钟不对齐。最好每秒更新多次。

You might think that setting the interval to 1000 ms would be ok, but you may find that it visually does not tick smoothly. That happens because the interval timer might not align with the actual clock. It's better to update multiple times per second.

这篇关于如何在特定时区使用moment.JS并实时显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆