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

前端 未结 1 1890
粉色の甜心
粉色の甜心 2021-02-15 18:30

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.

1条回答
  •  后悔当初
    2021-02-15 18:50

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题