1

enter image description here

I want to be able to customize the format of each day of month.

For example, I want to force them all to be 0 left padded. e.g. "01" "02"...

I'm using the moment version. I know how to format the month header, but not the individual days inside the month view.

It appears this is not currently supported directly by Material's Datepicker and I was hoping for a workaround.

https://github.com/angular/components/issues/13817

Matthew B.
  • 684
  • 8
  • 18

2 Answers2

2

It's not possible to customise the month view using angular material settings. As a workaround, you can use the solution below.

This is a hack, but you can manually modify the dates once the calendar open

component.html

<mat-datepicker (opened)="dtpOpened()" #picker></mat-datepicker>

component.ts

  public dtpOpened()
  {
    setTimeout(()=>
    {
      const cells = Array.from(document.querySelectorAll<HTMLDivElement>('.mat-calendar .mat-calendar-body-cell-content'));

      cells.forEach(c=>
      {
        c.innerText = c.innerText.length == 1?  '0' + c.innerText : c.innerText;

      });

    });

  }

Stackblitz demo

Note that this will only modify the displayed value on the month view. If you need to change custom format on the text input itself, you can provide a custom format, like in this answer.

David
  • 33,444
  • 11
  • 80
  • 118
-2

You can try to create you own DateAdapter and formats.

class MomentDateAdapter extends DateAdapter<Moment> {
    parse(value: any, parseFormat: any): Moment {
        return moment(value, parseFormat);
    }

    // Implementation for remaining abstract methods of DateAdapter.
}

const MOMENT_FORMATS = {
    parse: {
        dateInput: 'LL',
    },
    display: {
        monthYearLabel: 'MMM YYYY',
        // See DateFormats for other required formats.
    },
};

And provide both of these things in your application module:

@NgModule({
    imports: [MdDatepickerModule, ...],
    providers: [
        {provide: DateAdapter, useClass: MomentDateAdapter},
        {provide: MD_DATE_FORMATS, useValue: MOMENT_FORMATS},
    ],
})
class AppModule {}

Also you can try to find and set locale that use 01, 02 format instead of 1.2.

  • This works for everything BUT the day of month labels. If I'm wrong please provide a more detailed example that does it. – Matthew B. May 21 '20 at 12:30