angularangular-materialangular8angular-material2date-pipe

How can I customize date and time format in ngx-mat-datetime-picker?


I am working on Angular7 and its compatible ngx-mat-datetime-picker. It works as expected.

Want to customize the format:

Actual: mm/dd/yyyy, hh:mm:ss Expected: yyyy-mm-dd hh:mm:ss

Currently I don't find any option for formatting.

I tried something like this in template value="{{ mydate | date: 'yyyy-mm-dd hh:mm:ss' }}

But not working.


Solution

  • You need to create a custom adapter and specify the custom formats

    const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
      parse: {
        dateInput: 'l, LTS'
      },
      display: {
        dateInput: 'YYYY-MM-DD HH:mm:ss',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
      }
    };
    
    @NgModule({
      providers: [
        {
          provide: NgxMatDateAdapter,
          useClass: CustomNgxDatetimeAdapter,
          deps: [MAT_DATE_LOCALE, NGX_MAT_MOMENT_DATE_ADAPTER_OPTIONS]
        },
        { provide: NGX_MAT_DATE_FORMATS, useValue: CUSTOM_DATE_FORMATS }
      ],
    })
    export class CustomNgxDateTimeModule { }
    

    Please find the CustomNgxDatetimeAdapter.ts from the below gist

    https://gist.github.com/nandhakumargdr/635af05419793e15f3758656ddd1ef39

    enter image description here

    Have tested it. It is working!