How to change Mat-Datepicker date format to DD/MM/YYYY in simplest way?

后端 未结 9 1533
孤城傲影
孤城傲影 2021-02-07 09:00

I\'m setting up a mat-datepicker for DOB and traditionally the display format is MM/DD/YYYY,I need to change it to DD/MM/YYYY with less coding

I tried format tag in mat

9条回答
  •  無奈伤痛
    2021-02-07 09:32

    For me, the best approach was to inject MAT_DATE_FORMATS to my component, which then dynamically determines what should the display format look like.

    Setup in component:

      constructor(@Inject(MAT_DATE_FORMATS) private dateFormats) { }
    
      ngOnInit() {
        if (this.data.inputType === InputDateDialogRangeType.MonthAndYearOnly)
          this.dateFormats.display.dateInput = "MMMM YYYY";
        else if (this.data.inputType === InputDateDialogRangeType.YearOnly)
          this.dateFormats.display.dateInput = "YYYY";           
      }
    

    Setup in module:

     providers: [
        { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMAT },
        {
          provide: DateAdapter,
          useClass: MomentDateAdapter,
          deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
        },
        { provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: { useUtc: true } },
    
    export const MY_DATE_FORMAT = {
      display: {
        dateInput: 'DD MMM YYYY',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
      },
    };
    

提交回复
热议问题