CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-moment

Parse, validate, manipulate, and display dates and times in JavaScript with internationalization support

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

locale.mddocs/

Locale and Internationalization

Comprehensive internationalization system with support for 100+ locales, custom locale definitions, and locale-aware formatting for dates, times, and relative time expressions.

Capabilities

Global Locale Management

Static methods for managing the global locale setting and available locales.

/**
 * Get the current global locale
 * @returns Current global locale identifier
 */
function locale(): string;

/**
 * Set the global locale
 * @param language - Locale identifier to set globally
 * @returns The locale that was set (may differ if fallback occurred)
 */
function locale(language: string): string;

/**
 * Set global locale with fallback options
 * @param language - Array of locale identifiers (tries in order)
 * @returns The locale that was successfully set
 */
function locale(language: string[]): string;

/**
 * Define and set a custom locale
 * @param language - Locale identifier
 * @param definition - Locale specification object (can be null to remove)
 * @returns The locale that was set
 */
function locale(language: string, definition?: LocaleSpecification | void): string;

/**
 * Get locale data for a specific locale
 * @param key - Locale identifier(s) to get data for (defaults to current)
 * @returns Locale data object
 */
function localeData(key?: string | string[]): Locale;

/**
 * Get array of all available locale identifiers
 * @returns Array of locale identifier strings
 */
function locales(): string[];

Usage Examples:

import moment from "moment";

// Get current global locale
console.log(moment.locale()); // "en" (default)

// Set global locale
moment.locale("fr");
console.log(moment().format("LLLL")); // French formatting
console.log(moment.locale()); // "fr"

// Try multiple locales (fallback)
moment.locale(["es-mx", "es", "en"]); // Tries Spanish (Mexico), then Spanish, then English
console.log(moment.locale()); // "es" (if Spanish is available)

// Reset to English
moment.locale("en");

// Get available locales
const available = moment.locales();
console.log(available.length); // 100+
console.log(available.slice(0, 10)); // First 10 locales
// ["af", "ar", "ar-dz", "ar-kw", "ar-ly", "ar-ma", "ar-ps", "ar-sa", "ar-tn", "az"]

// Get locale data
const englishData = moment.localeData("en");
console.log(englishData.months()); // English month names
const frenchData = moment.localeData("fr");
console.log(frenchData.months()); // French month names

// Check if locale is available
const spanishData = moment.localeData("es");
if (spanishData._config.abbr === "es") {
  console.log("Spanish locale is available");
}

Instance Locale Methods

Methods for setting locale on individual Moment instances without affecting global settings.

/**
 * Get the locale of this moment instance
 * @returns Locale identifier for this instance
 */
locale(): string;

/**
 * Set the locale for this moment instance only
 * @param locale - Locale identifier to set for this instance
 * @returns This moment instance (for chaining)
 */
locale(locale: LocaleSpecifier): Moment;

/**
 * Get locale data for this moment instance
 * @returns Locale data object for this instance's locale
 */
localeData(): Locale;

type LocaleSpecifier = string | Moment | Duration | string[] | boolean;

Usage Examples:

import moment from "moment";

// Create moments with different locales
const date = moment("2023-12-25T15:30:00");
console.log(date.locale()); // "en" (inherits global)

// Set instance locale
const frenchDate = date.clone().locale("fr");
const germanDate = date.clone().locale("de");
const spanishDate = date.clone().locale("es");

// Format in different locales
console.log(date.format("LLLL")); // "Monday, December 25, 2023 3:30 PM"
console.log(frenchDate.format("LLLL")); // "lundi 25 décembre 2023 15:30"
console.log(germanDate.format("LLLL")); // "Montag, 25. Dezember 2023 15:30"
console.log(spanishDate.format("LLLL")); // "lunes, 25 de diciembre de 2023 15:30"

// Relative time in different locales
const past = moment().subtract(2, "hours");
console.log(past.fromNow()); // "2 hours ago"
console.log(past.clone().locale("fr").fromNow()); // "il y a 2 heures"
console.log(past.clone().locale("de").fromNow()); // "vor 2 Stunden"
console.log(past.clone().locale("es").fromNow()); // "hace 2 horas"

// Instance locale doesn't affect global
console.log(moment.locale()); // Still "en"
console.log(frenchDate.locale()); // "fr"

// Chain with other operations
const result = moment("2023-12-25")
  .locale("fr")
  .add(1, "month")
  .format("MMMM YYYY");
console.log(result); // "janvier 2024"

Display Name Functions

Static methods for getting localized display names for months, weekdays, etc.

/**
 * Get array of month names in current locale
 * @returns Array of full month names
 */
function months(): string[];

/**
 * Get month name for specific index
 * @param index - Month index (0-11)
 * @returns Month name for the given index
 */
function months(index: number): string;

/**
 * Get month names for specific format/locale
 * @param format - Format string for context
 * @returns Array of month names appropriate for format
 */
function months(format: string): string[];

/**
 * Get month name for specific index and format
 * @param format - Format string for context
 * @param index - Month index (0-11)
 * @returns Month name for given index and format
 */
function months(format: string, index: number): string;

/**
 * Get array of short month names
 * @returns Array of abbreviated month names
 */
function monthsShort(): string[];

// Similar overloads for monthsShort as months

/**
 * Get array of weekday names
 * @returns Array of full weekday names
 */
function weekdays(): string[];

/**
 * Get weekday name for specific index
 * @param index - Weekday index (0-6, Sunday = 0)
 * @returns Weekday name for the given index
 */
function weekdays(index: number): string;

/**
 * Get weekday names with locale sorting option
 * @param localeSorted - Whether to sort according to locale's first day of week
 * @returns Array of weekday names
 */
function weekdays(localeSorted: boolean): string[];

// Additional overloads for weekdays, weekdaysShort, weekdaysMin with various parameters
function weekdaysShort(): string[];
function weekdaysMin(): string[];

Usage Examples:

import moment from "moment";

// Month names in current locale
console.log(moment.months());
// ["January", "February", "March", ..., "December"]

console.log(moment.monthsShort());
// ["Jan", "Feb", "Mar", ..., "Dec"]

// Specific month
console.log(moment.months(0)); // "January"
console.log(moment.months(11)); // "December"
console.log(moment.monthsShort(5)); // "Jun"

// Weekday names
console.log(moment.weekdays());
// ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

console.log(moment.weekdaysShort());
// ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

console.log(moment.weekdaysMin());
// ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]

// Specific weekday
console.log(moment.weekdays(1)); // "Monday"
console.log(moment.weekdaysShort(5)); // "Fri"

// Change global locale and see the difference
moment.locale("fr");
console.log(moment.months());
// ["janvier", "février", "mars", ..., "décembre"]

console.log(moment.weekdays());
// ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"]

moment.locale("de");
console.log(moment.months());
// ["Januar", "Februar", "März", ..., "Dezember"]

// Locale-sorted weekdays (starts with locale's first day of week)
moment.locale("en");
console.log(moment.weekdays(false)); // Standard order (Sunday first)
console.log(moment.weekdays(true)); // Locale order (may vary)

// Context-specific formatting
console.log(moment.months("MMM")); // Short names context
console.log(moment.months("MMMM")); // Full names context

// Reset to English
moment.locale("en");

Custom Locale Definition

Methods for defining and updating custom locales.

/**
 * Define a new locale
 * @param language - Locale identifier for the new locale
 * @param localeSpec - Locale specification object defining the locale
 * @returns Locale data object for the defined locale
 */
function defineLocale(language: string, localeSpec: LocaleSpecification | void): Locale;

/**
 * Update an existing locale
 * @param language - Locale identifier to update
 * @param localeSpec - Partial locale specification to merge with existing
 * @returns Updated locale data object
 */
function updateLocale(language: string, localeSpec: LocaleSpecification | void): Locale;

interface LocaleSpecification {
  months?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
  monthsShort?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
  weekdays?: string[] | StandaloneFormatSpec | MonthWeekdayFn;
  weekdaysShort?: string[] | StandaloneFormatSpec | WeekdaySimpleFn;
  weekdaysMin?: string[] | StandaloneFormatSpec | WeekdaySimpleFn;
  meridiemParse?: RegExp;
  meridiem?: (hour: number, minute: number, isLower: boolean) => string;
  isPM?: (input: string) => boolean;
  longDateFormat?: LongDateFormatSpec;
  calendar?: CalendarSpec;
  relativeTime?: RelativeTimeSpec;
  invalidDate?: string;
  ordinal?: (n: number) => string;
  ordinalParse?: RegExp;
  week?: WeekSpec;
  eras?: EraSpec[];
  [x: string]: any; // Allow additional properties
}

interface StandaloneFormatSpec {
  format: string[];
  standalone: string[];
  isFormat?: RegExp;
}

interface WeekSpec {
  dow: number; // Day of week (0 = Sunday)
  doy?: number; // Day of year for week calculation
}

interface LongDateFormatSpec {
  LTS: string;    // Time with seconds
  LT: string;     // Time
  L: string;      // Date
  LL: string;     // Date with month name
  LLL: string;    // Date with month name and time
  LLLL: string;   // Date with day name, month name and time
  lts?: string;   // Lowercase variants
  lt?: string;
  l?: string;
  ll?: string;
  lll?: string;
  llll?: string;
}

Usage Examples:

import moment from "moment";

// Define a custom locale
moment.defineLocale("x-pseudo", {
  months: [
    "Ĵāñūārÿ", "Fēƀŕūārÿ", "Māŕċħ", "Āƥŕĩŀ", "Māÿ", "Ĵūñē",
    "Ĵūŀÿ", "Āūġūśţ", "Śēƥţēɱƀēŕ", "Ōċţōƀēŕ", "Ñōvēɱƀēŕ", "Ďēċēɱƀēŕ"
  ],
  monthsShort: ["Ĵāñ", "Fēƀ", "Māŕ", "Āƥŕ", "Māÿ", "Ĵūñ", "Ĵūŀ", "Āūġ", "Śēƥ", "Ōċţ", "Ñōv", "Ďēċ"],
  weekdays: ["Śūñďāÿ", "Māñďāÿ", "Ţūēśďāÿ", "Ŵēďñēśďāÿ", "Ţħūŕśďāÿ", "Fŕĩďāÿ", "Śāţūŕďāÿ"],
  weekdaysShort: ["Śūñ", "Māñ", "Ţūē", "Ŵēď", "Ţħū", "Fŕĩ", "Śāţ"],
  weekdaysMin: ["Śū", "Mā", "Ţū", "Ŵē", "Ţħ", "Fŕ", "Śā"],
  longDateFormat: {
    LT: "ĦĦ:ɱɱ",
    LTS: "ĦĦ:ɱɱ:śś",
    L: "ĎĎ/ĀĀ/ŸŸŸŸ",
    LL: "Ď ĀĀĀĀ ŸŸŸŸ",
    LLL: "Ď ĀĀĀĀ ŸŸŸŸ ĹŤ",
    LLLL: "ďďDD, Ď ĀĀĀĀ ŸŸŸŸ ĹŤ"
  },
  calendar: {
    sameDay: "[Ţōďāÿ āţ] LT",
    nextDay: "[Ţōɱōŕŕōŵ āţ] LT",
    nextWeek: "dddd [āţ] LT",
    lastDay: "[Ÿēśţēŕďāÿ āţ] LT",
    lastWeek: "[Ĺāśţ] dddd [āţ] LT",
    sameElse: "L"
  },
  relativeTime: {
    future: "ĩñ %s",
    past: "%s āġō",
    s: "ā fēŵ śēċōñďś",
    ss: "%d śēċōñďś",
    m: "ā ɱĩñūţē",
    mm: "%d ɱĩñūţēś",
    h: "āñ ħōūŕ",
    hh: "%d ħōūŕś",
    d: "ā ďāÿ",
    dd: "%d ďāÿś",
    M: "ā ɱōñţħ",
    MM: "%d ɱōñţħś",
    y: "ā ÿēāŕ",
    yy: "%d ÿēāŕś"
  },
  ordinal: function (number) {
    const b = number % 10;
    const output = (~~(number % 100 / 10) === 1) ? 'ţħ' :
                   (b === 1) ? 'śţ' :
                   (b === 2) ? 'ñď' :
                   (b === 3) ? 'ŕď' : 'ţħ';
    return number + output;
  }
});

// Use the custom locale
moment.locale("x-pseudo");
const pseudoDate = moment("2023-12-25T15:30:00");
console.log(pseudoDate.format("LLLL")); // "Māñďāÿ, 25ţħ Ďēċēɱƀēŕ 2023 15:30"
console.log(pseudoDate.fromNow()); // Pseudo-localized relative time

// Update existing locale
moment.updateLocale("en", {
  relativeTime: {
    future: "in %s",
    past: "%s ago",
    s: "a moment",
    ss: "%d seconds",
    m: "a minute",
    mm: "%d minutes",
    h: "an hour",
    hh: "%d hours",
    d: "a day",
    dd: "%d days",
    M: "a month",
    MM: "%d months",
    y: "a year",
    yy: "%d years"
  }
});

// Create business locale with custom week settings
moment.defineLocale("en-business", {
  parentLocale: "en",
  week: {
    dow: 1, // Monday is the first day of the week
    doy: 4  // The week that contains Jan 4th is the first week of the year
  },
  longDateFormat: {
    LT: "HH:mm",
    LTS: "HH:mm:ss",
    L: "YYYY-MM-DD",
    LL: "MMMM D, YYYY",
    LLL: "MMMM D, YYYY HH:mm",
    LLLL: "dddd, MMMM D, YYYY HH:mm"
  }
});

moment.locale("en-business");
console.log(moment().format("LLLL")); // Uses 24-hour format and Monday-first week

Locale Data Structure

Understanding the Locale interface and its methods.

interface Locale {
  // Calendar formatting
  calendar(key?: CalendarKey, m?: Moment, now?: Moment): string;
  
  // Date formatting
  longDateFormat(key: LongDateFormatKey): string;
  invalidDate(): string;
  ordinal(n: number): string;
  
  // Text processing
  preparse(inp: string): string;
  postformat(inp: string): string;
  
  // Relative time
  relativeTime(n: number, withoutSuffix: boolean, key: RelativeTimeKey, isFuture: boolean): string;
  pastFuture(diff: number, absRelTime: string): string;
  
  // Configuration
  set(config: Object): void;
  
  // Month handling
  months(): string[];
  months(m: Moment, format?: string): string;
  monthsShort(): string[];
  monthsShort(m: Moment, format?: string): string;
  monthsParse(monthName: string, format: string, strict: boolean): number;
  monthsRegex(strict: boolean): RegExp;
  monthsShortRegex(strict: boolean): RegExp;
  
  // Week handling
  week(m: Moment): number;
  firstDayOfYear(): number;
  firstDayOfWeek(): number;
  
  // Weekday handling
  weekdays(): string[];
  weekdays(m: Moment, format?: string): string;
  weekdaysMin(): string[];
  weekdaysMin(m: Moment): string;
  weekdaysShort(): string[];
  weekdaysShort(m: Moment): string;
  weekdaysParse(weekdayName: string, format: string, strict: boolean): number;
  weekdaysRegex(strict: boolean): RegExp;
  weekdaysShortRegex(strict: boolean): RegExp;
  weekdaysMinRegex(strict: boolean): RegExp;
  
  // Time parsing
  isPM(input: string): boolean;
  meridiem(hour: number, minute: number, isLower: boolean): string;
}

type CalendarKey = 'sameDay' | 'nextDay' | 'lastDay' | 'nextWeek' | 'lastWeek' | 'sameElse' | string;
type LongDateFormatKey = 'LTS' | 'LT' | 'L' | 'LL' | 'LLL' | 'LLLL' | 'lts' | 'lt' | 'l' | 'll' | 'lll' | 'llll';
type RelativeTimeKey = 's' | 'ss' | 'm' | 'mm' | 'h' | 'hh' | 'd' | 'dd' | 'w' | 'ww' | 'M' | 'MM' | 'y' | 'yy';

Usage Examples:

import moment from "moment";

// Get locale data and explore its methods
const localeData = moment.localeData("fr");

// Month operations
console.log(localeData.months()); // All French month names
console.log(localeData.months(moment("2023-05-01"), "MMMM")); // "mai"
console.log(localeData.monthsShort()); // Short French month names

// Weekday operations
console.log(localeData.weekdays()); // All French weekday names
console.log(localeData.firstDayOfWeek()); // 1 (Monday in France)

// Calendar formatting
const now = moment();
const tomorrow = moment().add(1, "day");
console.log(localeData.calendar("nextDay", tomorrow, now)); // "Demain à"

// Relative time
console.log(localeData.relativeTime(2, false, "h", true)); // "dans 2 heures"
console.log(localeData.relativeTime(2, false, "h", false)); // "il y a 2 heures"

// Ordinal formatting
console.log(localeData.ordinal(1)); // "1er" (first in French)
console.log(localeData.ordinal(2)); // "2e" (second in French)

// Meridiem (AM/PM)
console.log(localeData.meridiem(9, 30, false)); // Morning
console.log(localeData.meridiem(21, 30, false)); // Evening

// Date format expansion
console.log(localeData.longDateFormat("LLLL")); // Full format string
console.log(localeData.longDateFormat("L")); // Short date format

// Invalid date message
console.log(localeData.invalidDate()); // "Invalid date" or localized equivalent

Available Locales

Moment.js comes with 100+ built-in locales. Here are some examples:

Major Language Families

// Germanic languages
"en", "en-au", "en-ca", "en-gb", "en-ie", "en-nz"  // English variants
"de", "de-at", "de-ch"                              // German variants
"nl", "nl-be"                                       // Dutch variants
"da", "sv", "nb", "nn"                             // Scandinavian

// Romance languages  
"es", "es-do", "es-mx", "es-us"                    // Spanish variants
"fr", "fr-ca", "fr-ch"                             // French variants
"it", "it-ch"                                       // Italian variants
"pt", "pt-br"                                       // Portuguese variants
"ro"                                                // Romanian

// Slavic languages
"ru", "uk", "be"                                    // East Slavic
"pl", "cs", "sk"                                    // West Slavic  
"bg", "sr", "hr", "bs", "sl", "mk"                 // South Slavic

// Asian languages
"zh-cn", "zh-tw", "zh-hk", "zh-mo"                 // Chinese variants
"ja"                                                // Japanese
"ko"                                                // Korean
"hi", "bn", "gu", "te", "ta", "ml", "kn", "mr"    // Indian languages
"th", "vi", "km", "lo", "my"                       // Southeast Asian
"ar", "ar-dz", "ar-kw", "ar-ly", "ar-ma", "ar-ps", "ar-sa", "ar-tn"  // Arabic variants
"fa", "ur"                                          // Persian script
"he"                                                // Hebrew

// African languages
"af", "sw"                                          // Afrikaans, Swahili

// Other languages
"fi", "et", "lv", "lt"                             // Finno-Ugric/Baltic
"eu"                                                // Basque
"mt"                                                // Maltese
"ga", "cy", "br", "gd"                             // Celtic
"is", "fo"                                          // North Germanic islands
"ka", "hy-am", "az", "kk", "ky", "uz", "tk"       // Caucasian/Turkic
"eo"                                                // Esperanto
"x-pseudo"                                          // Pseudo-locale for testing

Locale Loading

import moment from "moment";

// Most locales are automatically available, but you can also import specific ones
import "moment/locale/fr";
import "moment/locale/de";
import "moment/locale/es";

// Or load multiple locales
import "moment/min/locales"; // All locales (increases bundle size)

// Check if a locale is available
console.log(moment.locales().includes("fr")); // true
console.log(moment.locales().includes("klingon")); // false

// Safe locale setting with fallback
function setLocaleSafely(locales) {
  const available = moment.locales();
  for (const locale of locales) {
    if (available.includes(locale)) {
      moment.locale(locale);
      return locale;
    }
  }
  return moment.locale(); // Return current if none found
}

const selectedLocale = setLocaleSafely(["fr-ca", "fr", "en"]);
console.log(`Using locale: ${selectedLocale}`);

Advanced Locale Interface Methods

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.

/**
 * Pre-process input strings before parsing
 * Used to normalize input text before moment parsing occurs
 * @param inp - Input string to preprocess
 * @returns Processed string ready for parsing
 */
preparse(inp: string): string;

/**
 * Post-process formatted output strings
 * Used to apply final formatting after moment formatting occurs
 * @param inp - Formatted string to postprocess
 * @returns Final processed output string
 */
postformat(inp: string): string;

/**
 * Parse month names to month numbers for this locale
 * @param monthName - Month name in the locale's language
 * @param format - Format string context for parsing
 * @param strict - Whether to use strict parsing rules
 * @returns Month number (0-11) or -1 if not found
 */
monthsParse(monthName: string, format: string, strict: boolean): number;

/**
 * Parse weekday names to weekday numbers for this locale
 * @param weekdayName - Weekday name in the locale's language
 * @param format - Format string context for parsing
 * @param strict - Whether to use strict parsing rules
 * @returns Weekday number (0-6) or -1 if not found
 */
weekdaysParse(weekdayName: string, format: string, strict: boolean): number;

/**
 * Get regex pattern for matching month names in this locale
 * @param strict - Whether to return strict or loose matching regex
 * @returns Regular expression for matching month names
 */
monthsRegex(strict: boolean): RegExp;

/**
 * Get regex pattern for matching weekday names in this locale
 * @param strict - Whether to return strict or loose matching regex
 * @returns Regular expression for matching weekday names
 */
weekdaysRegex(strict: boolean): RegExp;

/**
 * Format relative time with past/future context
 * @param diff - Time difference (positive for future, negative for past)
 * @param absRelTime - Absolute relative time string (e.g., "2 hours")
 * @returns Formatted string with past/future context (e.g., "in 2 hours" or "2 hours ago")
 */
pastFuture(diff: number, absRelTime: string): string;

/**
 * Update locale configuration dynamically
 * @param config - Configuration object with locale settings to update
 */
set(config: Object): void;

Usage Examples:

import moment from "moment";

// Get a locale data object for advanced operations
const localeData = moment.localeData("fr");

// Example 1: Text preprocessing and postprocessing
console.log(localeData.preparse("15 juin 2023")); // Normalize input
console.log(localeData.postformat("15 juin 2023")); // Apply final formatting

// Example 2: Month parsing
console.log(localeData.monthsParse("janvier", "MMMM", true)); // 0 (January)
console.log(localeData.monthsParse("janv", "MMM", true)); // 0 (January short)
console.log(localeData.monthsParse("invalid", "MMMM", true)); // -1 (not found)

// Example 3: Weekday parsing  
console.log(localeData.weekdaysParse("lundi", "dddd", true)); // 1 (Monday)
console.log(localeData.weekdaysParse("lun", "ddd", true)); // 1 (Monday short)
console.log(localeData.weekdaysParse("invalid", "dddd", true)); // -1 (not found)

// Example 4: Regex generation for parsing
const monthRegex = localeData.monthsRegex(true); // Strict month matching
const weekdayRegex = localeData.weekdaysRegex(false); // Loose weekday matching

console.log(monthRegex.test("janvier")); // true
console.log(monthRegex.test("jan")); // false (strict mode)

console.log(weekdayRegex.test("lundi")); // true  
console.log(weekdayRegex.test("lun")); // true (loose mode)

// Example 5: Past/Future formatting
console.log(localeData.pastFuture(5, "2 heures")); // "dans 2 heures" (future)
console.log(localeData.pastFuture(-5, "2 heures")); // "il y a 2 heures" (past)

// Example 6: Dynamic locale configuration
localeData.set({
  months: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jun", 
           "Jul", "Aoû", "Sep", "Oct", "Nov", "Déc"],
  weekdays: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"]
});

// Custom locale implementation using advanced methods
class CustomLocale {
  constructor(baseLocale) {
    this.base = moment.localeData(baseLocale);
  }

  // Override preparse to handle custom input formats
  preparse(input) {
    // Custom preprocessing logic
    return input
      .replace(/(\d+)er/, "$1") // Convert "1er" to "1"
      .replace(/(\d+)ème/, "$1"); // Convert "2ème" to "2"
  }

  // Override postformat to add custom styling
  postformat(output) {
    // Add custom styling or formatting
    return output.replace(/(\d+)/, "[$1]"); // Wrap numbers in brackets
  }

  // Use base locale methods with custom logic
  parseMonth(monthName) {
    const preprocessed = this.preparse(monthName);
    return this.base.monthsParse(preprocessed, "MMMM", true);
  }
}

// Usage of custom locale
const customFr = new CustomLocale("fr");
console.log(customFr.parseMonth("1er janvier")); // Uses custom preparse logic
console.log(customFr.postformat("25 décembre")); // "[25] décembre"

// Advanced parsing with regex
function parseAdvancedDate(input, locale = "en") {
  const localeData = moment.localeData(locale);
  const monthRegex = localeData.monthsRegex(false);
  const weekdayRegex = localeData.weekdaysRegex(false);
  
  let processedInput = localeData.preparse(input);
  
  // Use regex to identify components
  const monthMatch = processedInput.match(monthRegex);
  const weekdayMatch = processedInput.match(weekdayRegex);
  
  if (monthMatch) {
    const monthIndex = localeData.monthsParse(monthMatch[0], "MMMM", false);
    console.log(`Found month: ${monthMatch[0]} (index: ${monthIndex})`);
  }
  
  if (weekdayMatch) {
    const weekdayIndex = localeData.weekdaysParse(weekdayMatch[0], "dddd", false);
    console.log(`Found weekday: ${weekdayMatch[0]} (index: ${weekdayIndex})`);
  }
  
  return moment(processedInput);
}

// Test advanced parsing
parseAdvancedDate("lundi 15 janvier 2024", "fr");
parseAdvancedDate("Monday January 15th 2024", "en");

docs

comparison-validation.md

creation-parsing.md

display-formatting.md

duration.md

getters-setters.md

index.md

locale.md

manipulation.md

utilities.md

tile.json