简体   繁体   English

如何在特定时区使用moment.JS并实时显示

[英]How to use moment.JS for a certain timezone and display it in real time

How do I go about using the Moment.JS library for an international timezone and display it in real time? 如何将Moment.JS库用于国际时区并实时显示?

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>

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. 这是我第一次使用MomentJS,我不知道我是否正确实现了它并实时显示它而不经常刷新页面。

You are missing the actual zone data. 您缺少实际的区域数据。 Go to the moment-timezone data builder and include the zones you care about. 转到moment-timezone数据构建器并包含您关注的区域。 Put that in another file called moment-timezone-data.js and include it, or place it inline your existing script. 将它放在另一个名为moment-timezone-data.js文件中,并将其包含在内,或将其内联到现有脚本中。 See these docs . 请参阅这些文档

To update it in realtime, you need to update the element on a regular interval. 要实时更新它,您需要定期更新元素。

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. 而且你不需要jQuery。

Putting it all together: 把它们放在一起:

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

You might think that setting the interval to 1000 ms would be ok, but you may find that it visually does not tick smoothly. 您可能认为将间隔设置为1000毫秒就可以了,但您可能会发现它在视觉上不能顺利打勾。 That happens because the interval timer might not align with the actual clock. 发生这种情况是因为间隔计时器可能与实际时钟不对齐。 It's better to update multiple times per second. 最好每秒更新多次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM