Detect if user's locale is set to 12-hour or 24-hour timeformat using javascript

Viewed 1616

how to check whether the user is using 12hr or 24hr time format using Javascript with or without using 3rd party library like moment.js I also tried new Date().toLocaleString() but it is not working tested in firefox and google chrome. firefox always shows 12hr format and chrome always shows 24hrs time format

2 Answers

Mario Bonaci's answer didn't work as expected for me though it pointed me to the right direction. Here's what I tried at first:

/*
 * Detects navigator locale 24h time preference
 * It works by checking whether hour output contains AM ('1 AM' or '01 h')
 */
const isBrowserLocale24h = () =>
  !new Intl.DateTimeFormat(undefined, { hour: "numeric" })
    .format(0)
    .match(/AM/);

It didn't work as expected as it apparently takes the browser's install language and not the user preferred language. Changing the undefined to navigator.language did the trick. Here, we're checking the time format based on the user's preferred language:

/*
 * Detects navigator locale 24h time preference
 * It works by checking whether hour output contains AM ('1 AM' or '01 h')
 * based on the user's preferred language
 */
const isBrowserLocale24h = () =>
  !new Intl.DateTimeFormat(navigator.language, { hour: "numeric" })
    .format(0)
    .match(/AM/);

Something like this:

/*
 * Detects browser's locale 24h time preference
 * It works by checking whether hour output contains a space ('1 AM' or '01')
 */
const isBrowserLocale24h = () =>
  !new Intl.DateTimeFormat([], { hour: 'numeric' }).format(0).match(/\s/);

EDIT: Changed the first param from undefined to [] because the MDN docs say: To use the browser's default locale, pass an empty array.

Check browser compatibility of Intl.DateTimeFormat.

You can perhaps fallback to the following, but I'm not sure whether AM/PM designation (whichever characters are used) is at the end of the output for all locales. This just checks whether the last character is numeric:

Number.isFinite(Number((new Date()).toLocaleString().slice(-1)))
Related