Show Dates and Times in Viewers Local Time with JavaScript

By Eric Lathrop on

If you have a web site that shows dates and times, it can be confusing to people reading the site if they are displayed in a different time zone than what the person uses. With a little bit of JavaScript and the Luxon date library you can format your dates into the viewers local time zone.

Start with HTML like this:

<time data-format="MMM d, y t" datetime="2021-03-03T17:08:37.948155Z">
  Mar 03, 2021 05:08 PM

Notice that the time is shown in the UTC time zone.

The JavaScript below will find all <time> tags with data-format attributes when the page loads, and replace the inner text with the requested format of the time.

document.addEventListener("DOMContentLoaded", function() {
  var textProperty = "textContent" in document.body ? "textContent" : "innerText";
  var elements = document.querySelectorAll("time[data-format]");
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    var datetime = element.getAttribute("datetime");
    var format = element.getAttribute("data-format");

    element[textProperty] = luxon.DateTime.fromISO(datetime).toFormat(format);

This will make the above HTML render as Mar 3, 2021 12:08 PM. Notice that the time is shown in Eastern Standard Time.