How can I change date format in angular material datepicker?

无人久伴 提交于 2020-06-14 07:28:49

问题


I want to change the default date format (YYYY-MM-DD) to some other format like (MM-DD-YYYY).

This is my calendar HTML structure.

 <mat-form-field class="full-width">
                        <input matInput [matDatepicker]="picker"
                               [(ngModel)]="currentDay"
                               (dateChange)="currentDayChanged()"
                               required
                               placeholder="date"
                               name="currentDay">
                        <mat-datepicker-toggle matSuffix
                                               [for]="picker">
                        </mat-datepicker-toggle>
                        <mat-datepicker #picker></mat-datepicker>
                    </mat-form-field>

回答1:


There is a blog about it: https://blog.angular.io/taking-advantage-of-the-angular-material-datepicker-237e80fa14b3

(in case the URL becomes invalid), For example, say you’re already using Moment.js throughout your app, you can create a MomentDateAdapter:

Inherit a class

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

  // Implementation for remaining abstract methods of DateAdapter.
}

Create a const like this, f.e. in a separate typescript file:

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

finally 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 {}

I appreciate if you let us know your results.




回答2:


Set in AppModule your locale!

Example for Brazil,

import { LOCALE_ID } from '@angular/core';

import localePt from '@angular/common/locales/pt';
registerLocaleData(localePt, 'pt-BR');

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [],
    providers: [
      { provide: LOCALE_ID, useValue: 'pt-BR' }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }


来源:https://stackoverflow.com/questions/54669348/how-can-i-change-date-format-in-angular-material-datepicker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!