How to change angular material datepicker format

mmodalities picture mmodalities · Nov 18, 2018 · Viewed 64.2k times · Source

This is the format of date I am getting when I am using angular material datepicker....Wed Nov 21 2018 00:00:00 GMT+0530 (India Standard Time)

But I need date in (YYYY-MM-DD) or (YYYY-MM-DDTHH:mm) this format.

this is model class I am using to capture data from angular material form

export class FlightSchedule {

    constructor(
        public destination: string,
        public origin: string,
        public date: string,
        public limit: string
    ) {}

}

Please help me, I am unable to convert date in YYYY-MM-DD or YYYY-MM-DDTHH:mm format.

I am new to Angular

Thanks in advance

Answer

user184994 picture user184994 · Nov 18, 2018

You need to provide an object containing the formats you wish to use. The object should look something like:

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

You then need to add that in to your providers array, like so:

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

  //...

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

Here is a StackBlitz demo to show it working