Time Formatting in JavaScript

Feb 3, 2020 · 2 min read · 247 Words · -Views -Comments

I recently needed custom time formatting in a web app. After solving it, I documented it here.

Requirement 1: Use UTC (zero time zone)

To standardize time display, we needed to show time in UTC. Since we already use a shared date utility based on momentJS, we only needed to set the default time zone at web startup.

 
 moment.tz.setDefault('Africa/Abidjan');
 

Note: Africa/Abidjan is UTC.

Requirement 2: Display format based on system locale while keeping UTC

If the locale is en-us:

2/3/2020
February 3, 2020 at 3:18 PM

If the locale is en-gb:

03/02/2020
3 February 2020 at 15:17

Because time zone must stay UTC, moment formatting alone is not ideal: you either stick to a fixed time zone or manually specify a format. Fortunately, JS has toLocaleDateString.

Here is the solution:

# Date
moment().toDate().toLocaleDateString(navigator.language, {
  timeZone: moment.defaultZone.name
})

# Date + time
moment().toDate().toLocaleDateString(navigator.language, {
  timeStyle: 'short',
  dateStyle: 'long',
  timeZone: moment.defaultZone.name
})

Browser language

Since we rely on locale formatting, how do we test it? We need to understand browser language settings.

  1. Browsers default to the system language at install time.
  2. Browsers allow custom language settings, which may differ from the system. A web app should follow the browser language unless it has its own language logic. So you do not need to follow the OS language.
  3. For Chrome language settings, see here.
  4. Change the first language as above, refresh the web page, and you can test the display.

Final Thoughts

It is a small problem, but worth recording.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover