codemirror
codemirror

Reputation: 3572

How does Moment JS reads locale/language

I need to show date in localized format, so I used

moment().format('l');

function of Moment JS https://momentjs.com/#multiple-locale-support

It is not working as expected in different systems/browsers

root cause of the issue is that Moment reads current locale as "en" even when the environment is France ("fr")

console.log('moment lang: '+moment.lang());
console.log('userLanguage: '+window.navigator.userLanguage);
console.log('language: '+window.navigator.language);

Results produced:

moment lang: en
userLanguage: fr-FR
language: fr-FR

Moment will give correct locale formatted date if I explicitly set

moment().locale(window.navigator.userLanguage||window.navigator.language);

Do I really need to explicitly set locale in Moment or I am doing something wrong?

A note for duplicate question issue: question is how does Momentjs reads locale.

Upvotes: 2

Views: 1549

Answers (1)

VincenzoC
VincenzoC

Reputation: 31482

Yes you have set desired locale using moment.locale:

By default, Moment.js comes with English (United States) locale strings. If you need other locales, you can load them into Moment.js for later use.

To load a locale, pass the key and the string values to moment.locale.

Once you load a locale, it becomes the active locale. To change active locales, simply call moment.locale with the key of a loaded locale.

Please note tha lang is deprecated in 2.8.1

// Deprecated in 2.8.1
moment.lang(String);

Upvotes: 1

Related Questions