Skip to content

Instantly share code, notes, and snippets.

@isoboroff
Created November 17, 2021 19:23
Show Gist options
  • Save isoboroff/e368f83231e52a67f4f47da80946600e to your computer and use it in GitHub Desktop.
Save isoboroff/e368f83231e52a67f4f47da80946600e to your computer and use it in GitHub Desktop.
Updating times according to the viewer's timezone
<script src="moment.min.js"></script>
<script src="moment-timezone-with-data-10-year-range.js"></script>
<script>
const my_zone = moment.tz.guess(true);
// Set up timezone selector with all the zones.
// The user's current guessed zone is selected.
const sel = document.querySelector('select.timezone');
moment.tz.names().forEach( zone => {
option = document.createElement('option');
option.text = zone;
option.value = zone;
if (option.text == my_zone) {
option.selected = true;
}
sel.add(option);
});
// A function to update the times in the page.
const set_times = (to_zone) => {
document.querySelectorAll('th.time').forEach( el => {
const est = el.getAttribute("est");
const est_time = moment.tz(est, 'HH:mm', 'America/New_York');
const disp_time = est_time.tz(to_zone);
el.innerHTML = disp_time.format("HH:mm");
});
};
// Call set_times when the selector changes.
sel.addEventListener('change', (event) => {
set_times(event.target.value);
});
// And, when we come up, set times to the user's guessed zone.
set_times(my_zone);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment