javascript 如何在某个时区使用moment.JS并实时显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18793520/
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
How to use moment.JS for a certain timezone and display it in real time
提问by Jeiman
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,我不知道我是否正确实现了它并在不不断刷新页面的情况下实时显示它。
采纳答案by Matt Johnson-Pint
You are missing the actual zone data. Go to the moment-timezone data builderand 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.
您缺少实际的区域数据。转到moment-timezone 数据构建器并包含您关心的区域。将它放在另一个名为的文件中moment-timezone-data.js
并包含它,或者将它放在您现有的脚本中。请参阅这些文档。
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.
此外,在您的示例代码中,您第一次使用时区调用 moment 时,您正在丢弃响应。第二个电话,您没有使用时区。而且您在这里不需要 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. That happens because the interval timer might not align with the actual clock. It's better to update multiple times per second.
您可能认为将时间间隔设置为 1000 毫秒就可以了,但是您可能会发现它在视觉上并不流畅。发生这种情况是因为间隔计时器可能与实际时钟不一致。最好每秒更新多次。