When coding a website and formatting a date, I want to use the locale that the user has set in their browser.
So for example, if a user has customised their chrome://settings/languages
setting in Chrome to something non-default, that's the value I want to use.
However, when I run the code below in the console of such a browser, I get two different values.
[window.navigator.language, new Intl.DateTimeFormat().resolvedOptions().locale]
// Array [ "en-AU", "en-US" ]
navigator.language
gives me the expected value, but new Intl.DateTimeFormat().resolvedOptions().locale
does not.
MDN for both items seems (to me) to indicate that they should be returning the same value:
returns a string representing the preferred language of the user
To use the browser's default locale, omit this argument or pass undefined.
Should both of these calls be returning the locale the user configured in their browser settings?
I haven't visited this question for a long time, but it drew my attention back and I took another look at it. The documentation for these APIs has been improved, and I now think I know what's going on.
As previously stated, window.navigator.language
is indeed the "string representing the preferred language of the user" which is the one you can configure in your browser settings. You can also use window.navigator.languages
to get the ordered list of all the languages they've defined.
I had previous assumed that new Intl.DateTimeFormat().resolvedOptions().locale
would take the user's configured preferences into account internally, but I think that assumption is wrong. The Intl
functions appear to only use the locales that you explicitly pass to them, and if you don't pass any, it uses the "browser's default locale" NOT the browser user's default locale, and not the locale of the underlying OS.
So, if you actually run this:
new Intl.DateTimeFormat(window.navigator.languages).resolvedOptions().locale
Then you will get the locale that the DateTimeFormat is using, which was derived from the languages specified in order of preference by the user.
So, the lesson I've learned is, when using the Intl
functions, you should specify the locale(s) yourself.
Some additional links that may be useful: