0
# Locale and Internationalization
1
2
Comprehensive internationalization system with support for 100+ locales, custom locale definitions, and locale-aware formatting for dates, times, and relative time expressions.
3
4
## Capabilities
5
6
### Global Locale Management
7
8
Static methods for managing the global locale setting and available locales.
9
10
```javascript { .api }
11
/**
12
* Get the current global locale
13
* @returns Current global locale identifier
14
*/
15
function locale(): string;
16
17
/**
18
* Set the global locale
19
* @param language - Locale identifier to set globally
20
* @returns The locale that was set (may differ if fallback occurred)
21
*/
22
function locale(language: string): string;
23
24
/**
25
* Set global locale with fallback options
26
* @param language - Array of locale identifiers (tries in order)
27
* @returns The locale that was successfully set
28
*/
29
function locale(language: string[]): string;
30
31
/**
32
* Define and set a custom locale
33
* @param language - Locale identifier
34
* @param definition - Locale specification object (can be null to remove)
35
* @returns The locale that was set
36
*/
37
function locale(language: string, definition?: LocaleSpecification | void): string;
38
39
/**
40
* Get locale data for a specific locale
41
* @param key - Locale identifier(s) to get data for (defaults to current)
42
* @returns Locale data object
43
*/
44
function localeData(key?: string | string[]): Locale;
45
46
/**
47
* Get array of all available locale identifiers
48
* @returns Array of locale identifier strings
49
*/
50
function locales(): string[];
51
```
52
53
**Usage Examples:**
54
55
```javascript
56
import moment from "moment";
57
58
// Get current global locale
59
console.log(moment.locale()); // "en" (default)
60
61
// Set global locale
62
moment.locale("fr");
63
console.log(moment().format("LLLL")); // French formatting
64
console.log(moment.locale()); // "fr"
65
66
// Try multiple locales (fallback)
67
moment.locale(["es-mx", "es", "en"]); // Tries Spanish (Mexico), then Spanish, then English
68
console.log(moment.locale()); // "es" (if Spanish is available)
69
70
// Reset to English
71
moment.locale("en");
72
73
// Get available locales
74
const available = moment.locales();
75
console.log(available.length); // 100+
76
console.log(available.slice(0, 10)); // First 10 locales
77
// ["af", "ar", "ar-dz", "ar-kw", "ar-ly", "ar-ma", "ar-ps", "ar-sa", "ar-tn", "az"]
78
79
// Get locale data
80
const englishData = moment.localeData("en");
81
console.log(englishData.months()); // English month names
82
const frenchData = moment.localeData("fr");
83
console.log(frenchData.months()); // French month names
84
85
// Check if locale is available
86
const spanishData = moment.localeData("es");
87
if (spanishData._config.abbr === "es") {
88
console.log("Spanish locale is available");
89
}
90
```
91
92
### Instance Locale Methods
93
94
Methods for setting locale on individual Moment instances without affecting global settings.
95
96
```javascript { .api }
97
/**
98
* Get the locale of this moment instance
99
* @returns Locale identifier for this instance
100
*/
101
locale(): string;
102
103
/**
104
* Set the locale for this moment instance only
105
* @param locale - Locale identifier to set for this instance
106
* @returns This moment instance (for chaining)
107
*/
108
locale(locale: LocaleSpecifier): Moment;
109
110
/**
111
* Get locale data for this moment instance
112
* @returns Locale data object for this instance's locale
113
*/
114
localeData(): Locale;
115
116
type LocaleSpecifier = string | Moment | Duration | string[] | boolean;
117
```
118
119
**Usage Examples:**
120
121
```javascript
122
import moment from "moment";
123
124
// Create moments with different locales
125
const date = moment("2023-12-25T15:30:00");
126
console.log(date.locale()); // "en" (inherits global)
127
128
// Set instance locale
129
const frenchDate = date.clone().locale("fr");
130
const germanDate = date.clone().locale("de");
131
const spanishDate = date.clone().locale("es");
132
133
// Format in different locales
134
console.log(date.format("LLLL")); // "Monday, December 25, 2023 3:30 PM"
135
console.log(frenchDate.format("LLLL")); // "lundi 25 décembre 2023 15:30"
136
console.log(germanDate.format("LLLL")); // "Montag, 25. Dezember 2023 15:30"
137
console.log(spanishDate.format("LLLL")); // "lunes, 25 de diciembre de 2023 15:30"
138
139
// Relative time in different locales
140
const past = moment().subtract(2, "hours");
141
console.log(past.fromNow()); // "2 hours ago"
142
console.log(past.clone().locale("fr").fromNow()); // "il y a 2 heures"
143
console.log(past.clone().locale("de").fromNow()); // "vor 2 Stunden"
144
console.log(past.clone().locale("es").fromNow()); // "hace 2 horas"
145
146
// Instance locale doesn't affect global
147
console.log(moment.locale()); // Still "en"
148
console.log(frenchDate.locale()); // "fr"
149
150
// Chain with other operations
151
const result = moment("2023-12-25")
152
.locale("fr")
153
.add(1, "month")
154
.format("MMMM YYYY");
155
console.log(result); // "janvier 2024"
156
```
157
158
### Display Name Functions
159
160
Static methods for getting localized display names for months, weekdays, etc.
161
162
```javascript { .api }
163
/**
164
* Get array of month names in current locale
165
* @returns Array of full month names
166
*/
167
function months(): string[];
168
169
/**
170
* Get month name for specific index
171
* @param index - Month index (0-11)
172
* @returns Month name for the given index
173
*/
174
function months(index: number): string;
175
176
/**
177
* Get month names for specific format/locale
178
* @param format - Format string for context
179
* @returns Array of month names appropriate for format
180
*/
181
function months(format: string): string[];
182
183
/**
184
* Get month name for specific index and format
185
* @param format - Format string for context
186
* @param index - Month index (0-11)
187
* @returns Month name for given index and format
188
*/
189
function months(format: string, index: number): string;
190
191
/**
192
* Get array of short month names
193
* @returns Array of abbreviated month names
194
*/
195
function monthsShort(): string[];
196
197
// Similar overloads for monthsShort as months
198
199
/**
200
* Get array of weekday names
201
* @returns Array of full weekday names
202
*/
203
function weekdays(): string[];
204
205
/**
206
* Get weekday name for specific index
207
* @param index - Weekday index (0-6, Sunday = 0)
208
* @returns Weekday name for the given index
209
*/
210
function weekdays(index: number): string;
211
212
/**
213
* Get weekday names with locale sorting option
214
* @param localeSorted - Whether to sort according to locale's first day of week
215
* @returns Array of weekday names
216
*/
217
function weekdays(localeSorted: boolean): string[];
218
219
// Additional overloads for weekdays, weekdaysShort, weekdaysMin with various parameters
220
function weekdaysShort(): string[];
221
function weekdaysMin(): string[];
222
```
223
224
**Usage Examples:**
225
226
```javascript
227
import moment from "moment";
228
229
// Month names in current locale
230
console.log(moment.months());
231
// ["January", "February", "March", ..., "December"]
232
233
console.log(moment.monthsShort());
234
// ["Jan", "Feb", "Mar", ..., "Dec"]
235
236
// Specific month
237
console.log(moment.months(0)); // "January"
238
console.log(moment.months(11)); // "December"
239
console.log(moment.monthsShort(5)); // "Jun"
240
241
// Weekday names
242
console.log(moment.weekdays());
243
// ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
244
245
console.log(moment.weekdaysShort());
246
// ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
247
248
console.log(moment.weekdaysMin());
249
// ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
250
251
// Specific weekday
252
console.log(moment.weekdays(1)); // "Monday"
253
console.log(moment.weekdaysShort(5)); // "Fri"
254
255
// Change global locale and see the difference
256
moment.locale("fr");
257
console.log(moment.months());
258
// ["janvier", "février", "mars", ..., "décembre"]
259
260
console.log(moment.weekdays());
261
// ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]
262
263
moment.locale("de");
264
console.log(moment.months());
265
// ["Januar", "Februar", "März", ..., "Dezember"]
266
267
// Locale-sorted weekdays (starts with locale's first day of week)
268
moment.locale("en");
269
console.log(moment.weekdays(false)); // Standard order (Sunday first)
270
console.log(moment.weekdays(true)); // Locale order (may vary)
271
272
// Context-specific formatting
273
console.log(moment.months("MMM")); // Short names context
274
console.log(moment.months("MMMM")); // Full names context
275
276
// Reset to English
277
moment.locale("en");
278
```
279
280
### Custom Locale Definition
281
282
Methods for defining and updating custom locales.
283
284
```javascript { .api }
285
/**
286
* Define a new locale
287
* @param language - Locale identifier for the new locale
288
* @param localeSpec - Locale specification object defining the locale
289
* @returns Locale data object for the defined locale
290
*/
291
function defineLocale(language: string, localeSpec: LocaleSpecification | void): Locale;
292
293
/**
294
* Update an existing locale
295
* @param language - Locale identifier to update
296
* @param localeSpec - Partial locale specification to merge with existing
297
* @returns Updated locale data object
298
*/
299
function updateLocale(language: string, localeSpec: LocaleSpecification | void): Locale;
300
301
interface LocaleSpecification {
302
months?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
303
monthsShort?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
304
weekdays?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
305
weekdaysShort?: string[] | StandaloneFormatSpec | WeekdaySimpleFn;
306
weekdaysMin?: string[] | StandaloneFormatSpec | WeekdaySimpleFn;
307
meridiemParse?: RegExp;
308
meridiem?: (hour: number, minute: number, isLower: boolean) => string;
309
isPM?: (input: string) => boolean;
310
longDateFormat?: LongDateFormatSpec;
311
calendar?: CalendarSpec;
312
relativeTime?: RelativeTimeSpec;
313
invalidDate?: string;
314
ordinal?: (n: number) => string;
315
ordinalParse?: RegExp;
316
week?: WeekSpec;
317
eras?: EraSpec[];
318
[x: string]: any; // Allow additional properties
319
}
320
321
interface StandaloneFormatSpec {
322
format: string[];
323
standalone: string[];
324
isFormat?: RegExp;
325
}
326
327
interface WeekSpec {
328
dow: number; // Day of week (0 = Sunday)
329
doy?: number; // Day of year for week calculation
330
}
331
332
interface LongDateFormatSpec {
333
LTS: string; // Time with seconds
334
LT: string; // Time
335
L: string; // Date
336
LL: string; // Date with month name
337
LLL: string; // Date with month name and time
338
LLLL: string; // Date with day name, month name and time
339
lts?: string; // Lowercase variants
340
lt?: string;
341
l?: string;
342
ll?: string;
343
lll?: string;
344
llll?: string;
345
}
346
```
347
348
**Usage Examples:**
349
350
```javascript
351
import moment from "moment";
352
353
// Define a custom locale
354
moment.defineLocale("x-pseudo", {
355
months: [
356
"Ĵāñūārÿ", "Fēƀŕūārÿ", "Māŕċħ", "Āƥŕĩŀ", "Māÿ", "Ĵūñē",
357
"Ĵūŀÿ", "Āūġūśţ", "Śēƥţēɱƀēŕ", "Ōċţōƀēŕ", "Ñōvēɱƀēŕ", "Ďēċēɱƀēŕ"
358
],
359
monthsShort: ["Ĵāñ", "Fēƀ", "Māŕ", "Āƥŕ", "Māÿ", "Ĵūñ", "Ĵūŀ", "Āūġ", "Śēƥ", "Ōċţ", "Ñōv", "Ďēċ"],
360
weekdays: ["Śūñďāÿ", "Māñďāÿ", "Ţūēśďāÿ", "Ŵēďñēśďāÿ", "Ţħūŕśďāÿ", "Fŕĩďāÿ", "Śāţūŕďāÿ"],
361
weekdaysShort: ["Śūñ", "Māñ", "Ţūē", "Ŵēď", "Ţħū", "Fŕĩ", "Śāţ"],
362
weekdaysMin: ["Śū", "Mā", "Ţū", "Ŵē", "Ţħ", "Fŕ", "Śā"],
363
longDateFormat: {
364
LT: "ĦĦ:ɱɱ",
365
LTS: "ĦĦ:ɱɱ:śś",
366
L: "ĎĎ/ĀĀ/ŸŸŸŸ",
367
LL: "Ď ĀĀĀĀ ŸŸŸŸ",
368
LLL: "Ď ĀĀĀĀ ŸŸŸŸ ĹŤ",
369
LLLL: "ďďDD, Ď ĀĀĀĀ ŸŸŸŸ ĹŤ"
370
},
371
calendar: {
372
sameDay: "[Ţōďāÿ āţ] LT",
373
nextDay: "[Ţōɱōŕŕōŵ āţ] LT",
374
nextWeek: "dddd [āţ] LT",
375
lastDay: "[Ÿēśţēŕďāÿ āţ] LT",
376
lastWeek: "[Ĺāśţ] dddd [āţ] LT",
377
sameElse: "L"
378
},
379
relativeTime: {
380
future: "ĩñ %s",
381
past: "%s āġō",
382
s: "ā fēŵ śēċōñďś",
383
ss: "%d śēċōñďś",
384
m: "ā ɱĩñūţē",
385
mm: "%d ɱĩñūţēś",
386
h: "āñ ħōūŕ",
387
hh: "%d ħōūŕś",
388
d: "ā ďāÿ",
389
dd: "%d ďāÿś",
390
M: "ā ɱōñţħ",
391
MM: "%d ɱōñţħś",
392
y: "ā ÿēāŕ",
393
yy: "%d ÿēāŕś"
394
},
395
ordinal: function (number) {
396
const b = number % 10;
397
const output = (~~(number % 100 / 10) === 1) ? 'ţħ' :
398
(b === 1) ? 'śţ' :
399
(b === 2) ? 'ñď' :
400
(b === 3) ? 'ŕď' : 'ţħ';
401
return number + output;
402
}
403
});
404
405
// Use the custom locale
406
moment.locale("x-pseudo");
407
const pseudoDate = moment("2023-12-25T15:30:00");
408
console.log(pseudoDate.format("LLLL")); // "Māñďāÿ, 25ţħ Ďēċēɱƀēŕ 2023 15:30"
409
console.log(pseudoDate.fromNow()); // Pseudo-localized relative time
410
411
// Update existing locale
412
moment.updateLocale("en", {
413
relativeTime: {
414
future: "in %s",
415
past: "%s ago",
416
s: "a moment",
417
ss: "%d seconds",
418
m: "a minute",
419
mm: "%d minutes",
420
h: "an hour",
421
hh: "%d hours",
422
d: "a day",
423
dd: "%d days",
424
M: "a month",
425
MM: "%d months",
426
y: "a year",
427
yy: "%d years"
428
}
429
});
430
431
// Create business locale with custom week settings
432
moment.defineLocale("en-business", {
433
parentLocale: "en",
434
week: {
435
dow: 1, // Monday is the first day of the week
436
doy: 4 // The week that contains Jan 4th is the first week of the year
437
},
438
longDateFormat: {
439
LT: "HH:mm",
440
LTS: "HH:mm:ss",
441
L: "YYYY-MM-DD",
442
LL: "MMMM D, YYYY",
443
LLL: "MMMM D, YYYY HH:mm",
444
LLLL: "dddd, MMMM D, YYYY HH:mm"
445
}
446
});
447
448
moment.locale("en-business");
449
console.log(moment().format("LLLL")); // Uses 24-hour format and Monday-first week
450
```
451
452
### Locale Data Structure
453
454
Understanding the Locale interface and its methods.
455
456
```javascript { .api }
457
interface Locale {
458
// Calendar formatting
459
calendar(key?: CalendarKey, m?: Moment, now?: Moment): string;
460
461
// Date formatting
462
longDateFormat(key: LongDateFormatKey): string;
463
invalidDate(): string;
464
ordinal(n: number): string;
465
466
// Text processing
467
preparse(inp: string): string;
468
postformat(inp: string): string;
469
470
// Relative time
471
relativeTime(n: number, withoutSuffix: boolean, key: RelativeTimeKey, isFuture: boolean): string;
472
pastFuture(diff: number, absRelTime: string): string;
473
474
// Configuration
475
set(config: Object): void;
476
477
// Month handling
478
months(): string[];
479
months(m: Moment, format?: string): string;
480
monthsShort(): string[];
481
monthsShort(m: Moment, format?: string): string;
482
monthsParse(monthName: string, format: string, strict: boolean): number;
483
monthsRegex(strict: boolean): RegExp;
484
monthsShortRegex(strict: boolean): RegExp;
485
486
// Week handling
487
week(m: Moment): number;
488
firstDayOfYear(): number;
489
firstDayOfWeek(): number;
490
491
// Weekday handling
492
weekdays(): string[];
493
weekdays(m: Moment, format?: string): string;
494
weekdaysMin(): string[];
495
weekdaysMin(m: Moment): string;
496
weekdaysShort(): string[];
497
weekdaysShort(m: Moment): string;
498
weekdaysParse(weekdayName: string, format: string, strict: boolean): number;
499
weekdaysRegex(strict: boolean): RegExp;
500
weekdaysShortRegex(strict: boolean): RegExp;
501
weekdaysMinRegex(strict: boolean): RegExp;
502
503
// Time parsing
504
isPM(input: string): boolean;
505
meridiem(hour: number, minute: number, isLower: boolean): string;
506
}
507
508
type CalendarKey = 'sameDay' | 'nextDay' | 'lastDay' | 'nextWeek' | 'lastWeek' | 'sameElse' | string;
509
type LongDateFormatKey = 'LTS' | 'LT' | 'L' | 'LL' | 'LLL' | 'LLLL' | 'lts' | 'lt' | 'l' | 'll' | 'lll' | 'llll';
510
type RelativeTimeKey = 's' | 'ss' | 'm' | 'mm' | 'h' | 'hh' | 'd' | 'dd' | 'w' | 'ww' | 'M' | 'MM' | 'y' | 'yy';
511
```
512
513
**Usage Examples:**
514
515
```javascript
516
import moment from "moment";
517
518
// Get locale data and explore its methods
519
const localeData = moment.localeData("fr");
520
521
// Month operations
522
console.log(localeData.months()); // All French month names
523
console.log(localeData.months(moment("2023-05-01"), "MMMM")); // "mai"
524
console.log(localeData.monthsShort()); // Short French month names
525
526
// Weekday operations
527
console.log(localeData.weekdays()); // All French weekday names
528
console.log(localeData.firstDayOfWeek()); // 1 (Monday in France)
529
530
// Calendar formatting
531
const now = moment();
532
const tomorrow = moment().add(1, "day");
533
console.log(localeData.calendar("nextDay", tomorrow, now)); // "Demain à"
534
535
// Relative time
536
console.log(localeData.relativeTime(2, false, "h", true)); // "dans 2 heures"
537
console.log(localeData.relativeTime(2, false, "h", false)); // "il y a 2 heures"
538
539
// Ordinal formatting
540
console.log(localeData.ordinal(1)); // "1er" (first in French)
541
console.log(localeData.ordinal(2)); // "2e" (second in French)
542
543
// Meridiem (AM/PM)
544
console.log(localeData.meridiem(9, 30, false)); // Morning
545
console.log(localeData.meridiem(21, 30, false)); // Evening
546
547
// Date format expansion
548
console.log(localeData.longDateFormat("LLLL")); // Full format string
549
console.log(localeData.longDateFormat("L")); // Short date format
550
551
// Invalid date message
552
console.log(localeData.invalidDate()); // "Invalid date" or localized equivalent
553
```
554
555
## Available Locales
556
557
Moment.js comes with 100+ built-in locales. Here are some examples:
558
559
### Major Language Families
560
561
```javascript
562
// Germanic languages
563
"en", "en-au", "en-ca", "en-gb", "en-ie", "en-nz" // English variants
564
"de", "de-at", "de-ch" // German variants
565
"nl", "nl-be" // Dutch variants
566
"da", "sv", "nb", "nn" // Scandinavian
567
568
// Romance languages
569
"es", "es-do", "es-mx", "es-us" // Spanish variants
570
"fr", "fr-ca", "fr-ch" // French variants
571
"it", "it-ch" // Italian variants
572
"pt", "pt-br" // Portuguese variants
573
"ro" // Romanian
574
575
// Slavic languages
576
"ru", "uk", "be" // East Slavic
577
"pl", "cs", "sk" // West Slavic
578
"bg", "sr", "hr", "bs", "sl", "mk" // South Slavic
579
580
// Asian languages
581
"zh-cn", "zh-tw", "zh-hk", "zh-mo" // Chinese variants
582
"ja" // Japanese
583
"ko" // Korean
584
"hi", "bn", "gu", "te", "ta", "ml", "kn", "mr" // Indian languages
585
"th", "vi", "km", "lo", "my" // Southeast Asian
586
"ar", "ar-dz", "ar-kw", "ar-ly", "ar-ma", "ar-ps", "ar-sa", "ar-tn" // Arabic variants
587
"fa", "ur" // Persian script
588
"he" // Hebrew
589
590
// African languages
591
"af", "sw" // Afrikaans, Swahili
592
593
// Other languages
594
"fi", "et", "lv", "lt" // Finno-Ugric/Baltic
595
"eu" // Basque
596
"mt" // Maltese
597
"ga", "cy", "br", "gd" // Celtic
598
"is", "fo" // North Germanic islands
599
"ka", "hy-am", "az", "kk", "ky", "uz", "tk" // Caucasian/Turkic
600
"eo" // Esperanto
601
"x-pseudo" // Pseudo-locale for testing
602
```
603
604
### Locale Loading
605
606
```javascript
607
import moment from "moment";
608
609
// Most locales are automatically available, but you can also import specific ones
610
import "moment/locale/fr";
611
import "moment/locale/de";
612
import "moment/locale/es";
613
614
// Or load multiple locales
615
import "moment/min/locales"; // All locales (increases bundle size)
616
617
// Check if a locale is available
618
console.log(moment.locales().includes("fr")); // true
619
console.log(moment.locales().includes("klingon")); // false
620
621
// Safe locale setting with fallback
622
function setLocaleSafely(locales) {
623
const available = moment.locales();
624
for (const locale of locales) {
625
if (available.includes(locale)) {
626
moment.locale(locale);
627
return locale;
628
}
629
}
630
return moment.locale(); // Return current if none found
631
}
632
633
const selectedLocale = setLocaleSafely(["fr-ca", "fr", "en"]);
634
console.log(`Using locale: ${selectedLocale}`);
635
```
636
637
### Advanced Locale Interface Methods
638
639
Advanced methods available on Locale objects for text processing, parsing, and regex generation. These methods are typically used internally by Moment.js but can be useful for custom locale implementations or advanced locale manipulation.
640
641
```javascript { .api }
642
/**
643
* Pre-process input strings before parsing
644
* Used to normalize input text before moment parsing occurs
645
* @param inp - Input string to preprocess
646
* @returns Processed string ready for parsing
647
*/
648
preparse(inp: string): string;
649
650
/**
651
* Post-process formatted output strings
652
* Used to apply final formatting after moment formatting occurs
653
* @param inp - Formatted string to postprocess
654
* @returns Final processed output string
655
*/
656
postformat(inp: string): string;
657
658
/**
659
* Parse month names to month numbers for this locale
660
* @param monthName - Month name in the locale's language
661
* @param format - Format string context for parsing
662
* @param strict - Whether to use strict parsing rules
663
* @returns Month number (0-11) or -1 if not found
664
*/
665
monthsParse(monthName: string, format: string, strict: boolean): number;
666
667
/**
668
* Parse weekday names to weekday numbers for this locale
669
* @param weekdayName - Weekday name in the locale's language
670
* @param format - Format string context for parsing
671
* @param strict - Whether to use strict parsing rules
672
* @returns Weekday number (0-6) or -1 if not found
673
*/
674
weekdaysParse(weekdayName: string, format: string, strict: boolean): number;
675
676
/**
677
* Get regex pattern for matching month names in this locale
678
* @param strict - Whether to return strict or loose matching regex
679
* @returns Regular expression for matching month names
680
*/
681
monthsRegex(strict: boolean): RegExp;
682
683
/**
684
* Get regex pattern for matching weekday names in this locale
685
* @param strict - Whether to return strict or loose matching regex
686
* @returns Regular expression for matching weekday names
687
*/
688
weekdaysRegex(strict: boolean): RegExp;
689
690
/**
691
* Format relative time with past/future context
692
* @param diff - Time difference (positive for future, negative for past)
693
* @param absRelTime - Absolute relative time string (e.g., "2 hours")
694
* @returns Formatted string with past/future context (e.g., "in 2 hours" or "2 hours ago")
695
*/
696
pastFuture(diff: number, absRelTime: string): string;
697
698
/**
699
* Update locale configuration dynamically
700
* @param config - Configuration object with locale settings to update
701
*/
702
set(config: Object): void;
703
```
704
705
**Usage Examples:**
706
707
```javascript
708
import moment from "moment";
709
710
// Get a locale data object for advanced operations
711
const localeData = moment.localeData("fr");
712
713
// Example 1: Text preprocessing and postprocessing
714
console.log(localeData.preparse("15 juin 2023")); // Normalize input
715
console.log(localeData.postformat("15 juin 2023")); // Apply final formatting
716
717
// Example 2: Month parsing
718
console.log(localeData.monthsParse("janvier", "MMMM", true)); // 0 (January)
719
console.log(localeData.monthsParse("janv", "MMM", true)); // 0 (January short)
720
console.log(localeData.monthsParse("invalid", "MMMM", true)); // -1 (not found)
721
722
// Example 3: Weekday parsing
723
console.log(localeData.weekdaysParse("lundi", "dddd", true)); // 1 (Monday)
724
console.log(localeData.weekdaysParse("lun", "ddd", true)); // 1 (Monday short)
725
console.log(localeData.weekdaysParse("invalid", "dddd", true)); // -1 (not found)
726
727
// Example 4: Regex generation for parsing
728
const monthRegex = localeData.monthsRegex(true); // Strict month matching
729
const weekdayRegex = localeData.weekdaysRegex(false); // Loose weekday matching
730
731
console.log(monthRegex.test("janvier")); // true
732
console.log(monthRegex.test("jan")); // false (strict mode)
733
734
console.log(weekdayRegex.test("lundi")); // true
735
console.log(weekdayRegex.test("lun")); // true (loose mode)
736
737
// Example 5: Past/Future formatting
738
console.log(localeData.pastFuture(5, "2 heures")); // "dans 2 heures" (future)
739
console.log(localeData.pastFuture(-5, "2 heures")); // "il y a 2 heures" (past)
740
741
// Example 6: Dynamic locale configuration
742
localeData.set({
743
months: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jun",
744
"Jul", "Aoû", "Sep", "Oct", "Nov", "Déc"],
745
weekdays: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"]
746
});
747
748
// Custom locale implementation using advanced methods
749
class CustomLocale {
750
constructor(baseLocale) {
751
this.base = moment.localeData(baseLocale);
752
}
753
754
// Override preparse to handle custom input formats
755
preparse(input) {
756
// Custom preprocessing logic
757
return input
758
.replace(/(\d+)er/, "$1") // Convert "1er" to "1"
759
.replace(/(\d+)ème/, "$1"); // Convert "2ème" to "2"
760
}
761
762
// Override postformat to add custom styling
763
postformat(output) {
764
// Add custom styling or formatting
765
return output.replace(/(\d+)/, "[$1]"); // Wrap numbers in brackets
766
}
767
768
// Use base locale methods with custom logic
769
parseMonth(monthName) {
770
const preprocessed = this.preparse(monthName);
771
return this.base.monthsParse(preprocessed, "MMMM", true);
772
}
773
}
774
775
// Usage of custom locale
776
const customFr = new CustomLocale("fr");
777
console.log(customFr.parseMonth("1er janvier")); // Uses custom preparse logic
778
console.log(customFr.postformat("25 décembre")); // "[25] décembre"
779
780
// Advanced parsing with regex
781
function parseAdvancedDate(input, locale = "en") {
782
const localeData = moment.localeData(locale);
783
const monthRegex = localeData.monthsRegex(false);
784
const weekdayRegex = localeData.weekdaysRegex(false);
785
786
let processedInput = localeData.preparse(input);
787
788
// Use regex to identify components
789
const monthMatch = processedInput.match(monthRegex);
790
const weekdayMatch = processedInput.match(weekdayRegex);
791
792
if (monthMatch) {
793
const monthIndex = localeData.monthsParse(monthMatch[0], "MMMM", false);
794
console.log(`Found month: ${monthMatch[0]} (index: ${monthIndex})`);
795
}
796
797
if (weekdayMatch) {
798
const weekdayIndex = localeData.weekdaysParse(weekdayMatch[0], "dddd", false);
799
console.log(`Found weekday: ${weekdayMatch[0]} (index: ${weekdayIndex})`);
800
}
801
802
return moment(processedInput);
803
}
804
805
// Test advanced parsing
806
parseAdvancedDate("lundi 15 janvier 2024", "fr");
807
parseAdvancedDate("Monday January 15th 2024", "en");
808
```