Formatting time elements to match the current user’s locale

Matt Glaman
2 min readApr 29, 2021

I recently created a Live page to promote my upcoming live coding streams and ways to find my previous ones. I have the times listed. However, times are hard. I first shipped them without specifying the CDT timezone — sorry folks. But still, this is a pain and unfriendly to anyone in a different timezone.

Heck, I even have a hard time translating 24h time format from EDT to CDT, let alone UTC. So I wrote some vanilla JavaScript to transform the times into the current user’s locale — no dependencies!

Drupal outputs its datetime fields in a time element with the datetime attribute, which contains the datetime string. Here's an example:

<time datetime="2021-04-27T19:00:00Z">Tue, 04/27/2021 - 2:00PM CDT</time>

We can use the datetime property to alter the element's content to be formatted to the current user's locale. All we need to do is use the Date object. We can take the value from the datetime attribute and pass it to the Date object's constructor to create a new object.

(function () {
document.querySelectorAll('time').forEach((el) => {
const date = new Date(el.dateTime);
})
})();

Pretty easy, yeah? Then we just need to use the locale methods:

--

--

Matt Glaman

PHP software engineer, open source contributor, and speaker