Explain Codes LogoExplain Codes Logo

How do I change the language of moment.js?

javascript
internationalization
moment-js
locale
Alex KataevbyAlex Kataev·Oct 13, 2024
TLDR

Change the locale in Moment.js with locale(). Pass the specific language code directly.

Apply globally for all instances:

moment.locale('fr'); // D'accord, c'est le français!

Apply for a particular date instance:

var localDate = moment().locale('ja'); // Let's speak 日本語 for this date!

Display date in the chosen locale:

console.log(moment().format('LLLL')); // Konnichiwa, date-san!

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.

<script src="wherever/moment-with-locales.min.js"></script>

Setting language for all future moments

To universally mandate a new language:

moment.locale('it'); // Now, every new Moment.js instance says "Ciao"

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:

console.log(localDate.format('LLLL')); // Voila, the date in your chosen locale

Telling time with locales

Need to express relative time? Don't worry; your newly multilingual Moment can paint a picture of passing time:

console.log(localDate.fromNow()); // Time lapse in local flavor

Setting locales in React

In component-based frameworks like React, sprinkle locales in useEffect() or componentDidMount():

// Did you know Moment.js can speak German too? useEffect(() => { moment.locale('de'); }, []);

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:

bower install moment --save

Checking plugin locale support

Remember to check locales support in third-party Moment.js plugins: localization isn’t universal!