4

Was anyone successful with a datepicker with format 'DD.MM.YYYY' and momentjs? I think the documentation as well as the starblitz might be broken.

Here my MaterialModule (which is imported in my AppModule), but all my datepicker have format LL (24.6.2018) instead of DD.MM.YYYY (24.06.2018).

import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE, MatDatepickerModule} from '@angular/material';
import {MomentDateModule, MomentDateAdapter} from '@angular/material-moment-adapter';

export const MY_FORMATS = {
    parse: {
        dateInput: 'DD.MM.YYYY',
    },
    display: {
        dateInput: 'DD.MM.YYYY',
        monthYearLabel: 'MM YYYY',
        dateA11yLabel: 'DD.MM.YYYY',
        monthYearA11yLabel: 'MM YYYY',
    },
};

@NgModule({
    imports: [..., MatDatepickerModule, MomentDateModule, ...],
    exports: [..., MatDatepickerModule, MomentDateModule, ...],
    providers: [
        {provide: MAT_DATE_LOCALE, useValue: 'de'},
        {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
        {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
    ],
})

1 Answer 1

3

There are two methods that we can use to customise the date format with MomentJs, as described in docs:

  • Import the MatMomentDateModule in your application's root module, then provide MAT_DATE_FORMATS in main module or at component level:
import {MatMomentDateModule} from '@angular/material-moment-adapter';

// ..

const MY_FORMATS = {
  parse: {
    dateInput: 'DD.MM.YYYY',
  },
  display: {
    dateInput: 'DD.MM.YYYY',
    monthYearLabel: 'MM YYYY',
    dateA11yLabel: 'DD.MM.YYYY',
    monthYearA11yLabel: 'MM YYYY',
  },
};

// ..

@NgModule({
  imports: [
    MatDatepickerModule,
    MatMomentDateModule
  ],
  provide: [
     { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS }
  ]
})

Example: https://stackblitz.com/edit/angular-uzicfk


  • If importing MatMomentDateModule is not possible, we can use the MomentDateAdapter for DateAdapter provider, together with MAT_DATE_FORMATS:
import {MomentDateAdapter} from '@angular/material-moment-adapter';

// ..

@NgModule({
  provide: [
     { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
     { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] }
  ]
})

Example: https://stackblitz.com/edit/angular-uzicfk-8y2lwr

Examples are build on Angular Material v9

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.