CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-angular--material-moment-adapter

Angular Material date adapter that integrates Moment.js with Angular Material's date picker and related components

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

Angular Material Moment Adapter

Angular Material Moment Adapter is a date adapter library that integrates Moment.js with Angular Material's date picker and related components. It implements the DateAdapter interface from @angular/material/core to enable Angular Material components to work seamlessly with Moment.js date objects, providing comprehensive date parsing, formatting, and manipulation capabilities with full internationalization support.

Package Information

  • Package Name: @angular/material-moment-adapter
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @angular/material-moment-adapter moment

Core Imports

import { 
  MomentDateAdapter, 
  MomentDateModule, 
  MatMomentDateModule,
  provideMomentDateAdapter,
  MAT_MOMENT_DATE_FORMATS,
  MAT_MOMENT_DATE_ADAPTER_OPTIONS,
  MAT_MOMENT_DATE_ADAPTER_OPTIONS_FACTORY,
  MatMomentDateAdapterOptions
} from '@angular/material-moment-adapter';

For CommonJS:

const { 
  MomentDateAdapter, 
  MomentDateModule, 
  MatMomentDateModule,
  provideMomentDateAdapter 
} = require('@angular/material-moment-adapter');

Basic Usage

import { NgModule } from '@angular/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatMomentDateModule } from '@angular/material-moment-adapter';

@NgModule({
  imports: [
    MatDatepickerModule,
    MatMomentDateModule,
  ],
})
export class MyModule {}

Alternative using provider function:

import { NgModule } from '@angular/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { provideMomentDateAdapter } from '@angular/material-moment-adapter';

@NgModule({
  imports: [MatDatepickerModule],
  providers: [provideMomentDateAdapter()],
})
export class MyModule {}

Architecture

The Angular Material Moment Adapter is built around several key components:

  • MomentDateAdapter: Core adapter class implementing Angular Material's DateAdapter interface
  • Angular Modules: Both traditional (MomentDateModule) and modern (MatMomentDateModule) module patterns
  • Provider Functions: Modern Angular provider functions for flexible configuration
  • Configuration Options: Type-safe options for customizing adapter behavior
  • Date Formats: Predefined Moment.js format configurations optimized for Material Design

Capabilities

Date Adapter

Core date adapter implementation that bridges Moment.js and Angular Material components.

/**
 * Adapts Moment.js Dates for use with Angular Material components
 */
class MomentDateAdapter extends DateAdapter<Moment> {
  constructor(...args: unknown[]);
  
  /** Set the adapter locale */
  setLocale(locale: string): void;
  
  /** Extract year from date */
  getYear(date: Moment): number;
  
  /** Extract month from date (0-based) */
  getMonth(date: Moment): number;
  
  /** Extract day of month from date */
  getDate(date: Moment): number;
  
  /** Extract day of week from date */
  getDayOfWeek(date: Moment): number;
  
  /** Get month names array for specified style */
  getMonthNames(style: 'long' | 'short' | 'narrow'): string[];
  
  /** Get date names (1-31) array */
  getDateNames(): string[];
  
  /** Get day of week names array for specified style */
  getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[];
  
  /** Get formatted year string */
  getYearName(date: Moment): string;
  
  /** Get first day of week for current locale */
  getFirstDayOfWeek(): number;
  
  /** Get number of days in the month */
  getNumDaysInMonth(date: Moment): number;
  
  /** Clone date with current locale */
  clone(date: Moment): Moment;
  
  /** Create new date from year, month, and day */
  createDate(year: number, month: number, date: number): Moment;
  
  /** Get current date */
  today(): Moment;
  
  /** Parse date from string or other input */
  parse(value: unknown, parseFormat: string | string[]): Moment | null;
  
  /** Format date to string using specified format */
  format(date: Moment, displayFormat: string): string;
  
  /** Add years to date */
  addCalendarYears(date: Moment, years: number): Moment;
  
  /** Add months to date */
  addCalendarMonths(date: Moment, months: number): Moment;
  
  /** Add days to date */
  addCalendarDays(date: Moment, days: number): Moment;
  
  /** Convert date to ISO 8601 string */
  toIso8601(date: Moment): string;
  
  /** Deserialize value to Moment date or null */
  deserialize(value: unknown): Moment | null;
  
  /** Check if object is a Moment instance */
  isDateInstance(obj: unknown): obj is Moment;
  
  /** Check if date is valid */
  isValid(date: Moment): boolean;
  
  /** Create invalid date */
  invalid(): Moment;
  
  /** Set time components on date */
  setTime(target: Moment, hours: number, minutes: number, seconds: number): Moment;
  
  /** Get hours from date */
  getHours(date: Moment): number;
  
  /** Get minutes from date */
  getMinutes(date: Moment): number;
  
  /** Get seconds from date */
  getSeconds(date: Moment): number;
  
  /** Parse time from string or other input */
  parseTime(value: unknown, parseFormat: string | string[]): Moment | null;
  
  /** Add seconds to date */
  addSeconds(date: Moment, amount: number): Moment;
}

Angular Modules

Pre-configured Angular modules for easy integration.

/**
 * Traditional Angular module providing MomentDateAdapter
 */
@NgModule()
class MomentDateModule {}

/**
 * Modern Angular module using provider functions
 */
@NgModule()
class MatMomentDateModule {}

Provider Functions

Modern Angular provider functions for flexible configuration.

/**
 * Provider function for configuring MomentDateAdapter with custom formats and options
 * @param formats - Custom date formats (defaults to MAT_MOMENT_DATE_FORMATS)
 * @param options - Adapter configuration options
 * @returns Array of Angular providers
 */
function provideMomentDateAdapter(
  formats?: MatDateFormats,
  options?: MatMomentDateAdapterOptions
): Provider[];

Usage Example:

import { provideMomentDateAdapter } from '@angular/material-moment-adapter';

// Basic usage
providers: [provideMomentDateAdapter()]

// With custom options
providers: [provideMomentDateAdapter(undefined, { 
  strict: true, 
  useUtc: true 
})]

// With custom formats
const customFormats = {
  parse: { dateInput: 'DD/MM/YYYY' },
  display: { dateInput: 'DD/MM/YYYY' }
};
providers: [provideMomentDateAdapter(customFormats)]

Configuration Options

Type-safe configuration options for customizing adapter behavior.

/**
 * Configuration options for MomentDateAdapter
 */
interface MatMomentDateAdapterOptions {
  /**
   * When enabled, dates must match the format exactly
   * See https://momentjs.com/guides/#/parsing/strict-mode/
   */
  strict?: boolean;
  
  /**
   * Turns the use of UTC dates on or off
   * Changing this affects how Angular Material components output dates
   * Defaults to false
   */
  useUtc?: boolean;
}

Injection Tokens

Dependency injection tokens for configuring the adapter.

/**
 * Injection token for moment date adapter configuration options
 */
const MAT_MOMENT_DATE_ADAPTER_OPTIONS: InjectionToken<MatMomentDateAdapterOptions>;

Factory Functions (Deprecated)

/**
 * @docs-private
 * @deprecated No longer used, will be removed.
 * @breaking-change 21.0.0
 * @returns Default adapter options with useUtc: false
 */
function MAT_MOMENT_DATE_ADAPTER_OPTIONS_FACTORY(): MatMomentDateAdapterOptions;

Date Formats

Predefined date formats optimized for Angular Material components.

/**
 * Default date formats for Moment.js adapter
 */
const MAT_MOMENT_DATE_FORMATS: MatDateFormats;

The format object structure:

interface MatDateFormats {
  parse: {
    dateInput: string;
    timeInput: string;
  };
  display: {
    dateInput: string;
    timeInput: string;
    monthYearLabel: string;
    dateA11yLabel: string;
    monthYearA11yLabel: string;
    timeOptionLabel: string;
  };
}

Default values in MAT_MOMENT_DATE_FORMATS:

  • parse.dateInput: 'l' (localized date)
  • parse.timeInput: 'LT' (localized time)
  • display.dateInput: 'l' (localized date)
  • display.timeInput: 'LT' (localized time)
  • display.monthYearLabel: 'MMM YYYY' (e.g., "Jan 2023")
  • display.dateA11yLabel: 'LL' (accessibility label)
  • display.monthYearA11yLabel: 'MMMM YYYY' (accessibility label)
  • display.timeOptionLabel: 'LT' (time picker label)

Types

/**
 * Moment.js date object type (from the 'moment' package)
 * Core interface for date manipulation and formatting
 */
interface Moment {
  /** Get the year */
  year(): number;
  /** Get the month (0-based) */
  month(): number;
  /** Get the date of month */
  date(): number;
  /** Get the day of week */
  day(): number;
  /** Get the hours */
  hours(): number;
  /** Get the minutes */
  minutes(): number;
  /** Get the seconds */
  seconds(): number;
  /** Format the date using given format string */
  format(format?: string): string;
  /** Create a clone of this moment */
  clone(): Moment;
  /** Get or set the locale */
  locale(): string;
  locale(locale: string): Moment;
  /** Check if the moment is valid */
  isValid(): boolean;
  /** Get number of days in the month */
  daysInMonth(): number;
  /** Add time to the moment */
  add(amount: number | object, unit?: string): Moment;
  /** Set time components */
  set(unit: string | object, value?: number): Moment;
}

Common Usage Patterns

Setting Up with Custom Locale

import { LOCALE_ID } from '@angular/core';
import { MatMomentDateModule } from '@angular/material-moment-adapter';

@NgModule({
  imports: [MatMomentDateModule],
  providers: [
    { provide: LOCALE_ID, useValue: 'en-GB' }
  ]
})
export class MyModule {}

Using with Strict Parsing

import { provideMomentDateAdapter } from '@angular/material-moment-adapter';

@NgModule({
  providers: [
    provideMomentDateAdapter(undefined, { strict: true })
  ]
})
export class MyModule {}

UTC Date Handling

import { provideMomentDateAdapter } from '@angular/material-moment-adapter';

@NgModule({
  providers: [
    provideMomentDateAdapter(undefined, { useUtc: true })
  ]
})
export class MyModule {}

Error Handling

The adapter throws descriptive errors for invalid input:

  • Invalid month: "Invalid month index "{month}". Month index has to be between 0 and 11."
  • Invalid date: "Invalid date "{date}". Date has to be greater than 0."
  • Invalid date for month: "Invalid date "{date}" for month with index "{month}"."
  • Invalid time components: "Invalid hours/minutes/seconds "{value}". Value must be between {min} and {max}."
  • Invalid date formatting: "MomentDateAdapter: Cannot format invalid date."

Dependencies

  • Angular Core: @angular/core (peer dependency)
  • Angular Material: @angular/material (peer dependency)
  • Moment.js: moment ^2.18.1 (peer dependency)
  • TypeScript Lib: tslib ^2.3.0

Browser Support

Supports all browsers that support Angular and Moment.js. The adapter works in both browser and Node.js environments when properly configured.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@angular/material-moment-adapter@20.2.x
Publish Source
CLI
Badge
tessl/npm-angular--material-moment-adapter badge