How do I change the language of moment.js?
Change the locale in Moment.js with locale()
. Pass the specific language code directly.
Apply globally for all instances:
Apply for a particular date instance:
Display date in the chosen locale:
Take note: If you're using version 2.8 or newer, the locale()
replaces the deprecated lang()
. Ensure your locale file like 'moment/locale/fr' is imported before usage.
Essential aspects of internationalization
Using the bundled locales
Moment.js includes a whopping 130+ locales out of the box. To access them all, include the moment-with-locales.min.js
file furnishing a United Nations summit in your app.
Setting language for all future moments
To universally mandate a new language:
Remember: Using locale()
on an instance affects only that instance. Without an explicit instance, it changes the global setting.
Getting localized date/time
After soaking up the new language skills, your dates can eloquently whisper the time in your ear:
Telling time with locales
Need to express relative time? Don't worry; your newly multilingual Moment can paint a picture of passing time:
Setting locales in React
In component-based frameworks like React, sprinkle locales in useEffect()
or componentDidMount()
:
Localization in practice
Minimizing bundle size
Import only necessary locales where possible: your users and their bandwidth will thank you.
Dealing with deprecated methods
Moment.js grew up and left lang()
behind — it's now all about locale()
.
Using Bower for better performance
If the ghost of web past (a.k.a Bower) haunts your project:
Checking plugin locale support
Remember to check locales support in third-party Moment.js plugins: localization isn’t universal!
Was this article helpful?