jeti
jeti

Reputation: 1908

Angular material2 Moment.js formatting

I want to display the year, month, day, hours, minutes and seconds in the input part of my material datepicker.
I've successfully overriden the parse() and format() methods in my custom DateAdapter using native Javascript objects.

However, now I want to use Moment.js. I've set up MomentDateAdapter and MAT_MOMENT_DATE_FORMATS as in the offical tutorial.

How can I change the formatting of my dates? Do I have to override the format() and parse() methods again, extending MomentDateAdapter?

Upvotes: 1

Views: 464

Answers (1)

Rui Marques
Rui Marques

Reputation: 8914

In the module where you import MomentDateAdapter, you can configure the formats the following way:

import {
  MAT_DATE_FORMATS,
  DateAdapter,
  MAT_DATE_LOCALE
} from '@angular/material';

// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
  parse: {
    dateInput: 'L'
  },
  display: {
    dateInput: 'L',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY'
  }
};

//...
providers: [
    { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
    { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }
]

Upvotes: 1

Related Questions