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

后端 未结 9 1415
孤城傲影
孤城傲影 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:29

    add to the providers list:

    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
    
    0 讨论(0)
  • 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',
      },
    };
    
    0 讨论(0)
  • 2021-02-07 09:37

    The easiest way is to change the locale:

    Add the following to the providers section of your module:

    { provide: MAT_DATE_LOCALE, useValue: 'en-GB' }
    
    0 讨论(0)
提交回复
热议问题