0

I have a table in a html page that has sites across the country. I want to add a column with the current time at each site.

There are three problems that I need to solve. First is how to have multiple clock on the same page. Second is having them in different time zones. Third is dealing with daylight savings time.

I have tried a couple different html and JavaScript clock but cannot get more that one instance to display.

I've figured out how to modify the clocks to add or subtract hours, but I haven't figured out how to display different clocks at the same time.

One of the sites is in AZ where they don't do daylight savings time. So it would be nice to use something like Moment Timezone to control the different clocks.

I'm very limited in my understanding of JavaScript, so I could really use some help figuring this stuff out. I really haven't found anything that tells me how to fix my problems in simple enough language for me to understand.

mouseskowitz
  • 45
  • 2
  • 9
  • @le_m Thanks. Like I said, I have a very limited understanding of what I'm doing here. – mouseskowitz May 20 '17 at 02:07
  • 1
    You can use this https://momentjs.com/timezone/ – alessandrio May 20 '17 at 02:16
  • [https://www.timeanddate.com/clocks/free.html] might be help. In case you just need to add the clock and don't require any further customization. It would also require less logic. Apply it as a Iframe on your website. – Rohit Kumar May 20 '17 at 03:18

1 Answers1

5

You can use Date.toLocaleTimeString() and provide a time zone within the options argument:

const clocks = document.getElementsByClassName("clock");

function updateClocks() {
  for (let clock of clocks) {
    let timezone = clock.dataset.timezone;
    let time = new Date().toLocaleTimeString("en-US", {
      hour: '2-digit',
      minute:'2-digit',
      timeZone: timezone
    });
    clock.textContent = time;
  }
}

// Update every minute:
setInterval(updateClocks, 60000);
updateClocks();
.clock {
   font-family: sans-serif;
   border: thin solid;
   border-radius: 10px;
   padding: 5px;
}
<p>New York: <span class="clock" data-timezone="America/New_York"></span></p>
<p>Shanghai: <span class="clock" data-timezone="Asia/Shanghai"></span></p>
<p>Berlin: <span class="clock" data-timezone="Europe/Berlin"></span></p>
le_m
  • 19,302
  • 9
  • 64
  • 74
  • That's perfect, thank you! Is there a way to just have h:m instead of h:m:s? – mouseskowitz May 20 '17 at 03:15
  • 1
    @mouseskowitz See updated answer and also http://stackoverflow.com/questions/17913681/how-do-i-use-tolocaletimestring-without-displaying-seconds – le_m May 20 '17 at 03:17