MomentJS - Internationalization
Modern Date/Time: Internationalization (i18n) with Moment.js
Section titled “Modern Date/Time: Internationalization (i18n) with Moment.js”Displaying dates and times in a user’s local language and format (Internationalization or i18n) is crucial for global applications. Moment.js provides robust support for locales.
While Moment.js handles i18n well, its approach involves loading locale data, which can increase bundle size. Modern alternatives like Day.js offer on-demand locale loading, and the native Intl API is specifically designed for i18n, often being the most efficient choice.
Loading Locales
Section titled “Loading Locales”To use locales other than the default (English), you need to load their definition files.
- All Locales (Browser): Include
moment-with-locales.js(ormoment-with-locales.min.js) instead of the standardmoment.js. This bundles all available locales but significantly increases file size. -
<script src="path/to/moment-with-locales.min.js"></script>
- Specific Locales (Browser/Bundlers): Load only the locales you need. This is the recommended approach for performance.
-
// Using ES6 imports with a bundler (Webpack, Rollup, etc.)import moment from 'moment';import 'moment/locale/fr'; // Load Frenchimport 'moment/locale/es'; // Load Spanish// Using require in Node.js or older bundler setupsconst moment = require('moment');require('moment/locale/de'); // Load German
- Node.js: When installed via npm (
npm install moment), all locale files are typically included withinnode_modules/moment/locale/and can be required as shown above.
Setting and Switching Locales
Section titled “Setting and Switching Locales”You can set locales globally or per-instance:
- Global Locale:
moment.locale(String)sets the locale for all subsequent Moment operations. It returns the name of the successfully set locale. - Local Locale:
momentInstance.locale(String)sets the locale only for that specific Moment instance and any moments cloned from it. This is useful for handling multiple locales simultaneously. - Getting Locale:
moment.locale()(global) ormomentInstance.locale()(local) returns the currently active locale string.
import moment from 'moment';import 'moment/locale/fr';import 'moment/locale/es';
// Set the global locale to Frenchmoment.locale('fr');console.log(moment().format('LLLL')); // Output: e.g., jeudi 26 octobre 2023 15:30console.log(moment.locale()); // Output: fr
// Create a moment and set its locale locally to Spanishconst spanishTime = moment().locale('es');console.log(spanishTime.format('LLLL')); // Output: e.g., jueves, 26 de octubre de 2023 15:30
// The global locale remains Frenchconsole.log(moment().format('LLLL')); // Output: e.g., jeudi 26 octobre 2023 15:30
// Revert global locale to English (default)moment.locale('en');console.log(moment().format('LLLL')); // Output: e.g., Thursday, October 26, 2023 3:30 PMLocale-Aware Formatting and Parsing
Section titled “Locale-Aware Formatting and Parsing”Once a locale is active (globally or locally), many Moment.js functions become locale-aware:
.format(): Uses localized month/weekday names and locale-specific long date formats (L, LL, LLL, LLLL)..fromNow(),.from(),.toNow(),.to(): Display relative times using localized units..calendar(): Produces localized calendar time strings.- Parsing (
moment(string, format, locale)): Can parse localized month and weekday names if the locale is specified during parsing.
moment.locale('de'); // Set German locale
// Formattingconsole.log(moment().format('dddd, Do MMMM YYYY')); // Output: Donnerstag, 26. Oktober 2023console.log(moment().subtract(2, 'days').calendar()); // Output: Vorgestern um 15:30 Uhr
// Parsingconst parsedDate = moment('Di., 24. Okt. 2023', 'ddd, D. MMM YYYY', 'de');console.log(parsedDate.isValid()); // trueconsole.log(parsedDate.format('YYYY-MM-DD')); // 2023-10-24Accessing Locale Data
Section titled “Accessing Locale Data”You can directly access data for the currently loaded locales:
moment.months(): Array of full month names.moment.monthsShort(): Array of short month names.moment.weekdays(): Array of full weekday names (Sunday-Saturday).moment.weekdaysShort(): Array of short weekday names.moment.weekdaysMin(): Array of minimal weekday names.moment.localeData(localeName): Get the full locale data object for a specific locale (or the current one if no name provided).
moment.locale('fr');console.log(moment.months()); // Output: ['janvier', 'février', ...]console.log(moment.weekdaysShort()); // Output: ['dim.', 'lun.', ...]
const frLocaleData = moment.localeData('fr');console.log(frLocaleData.firstDayOfWeek()); // Output: 1 (Monday)Internationalization is a key strength of Moment.js, but managing locale file loading and its impact on bundle size is an important consideration for modern web development.
See the official i18n documentation: https://momentjs.com/docs/#/i18n/