Change format of md-datepicker in Angular Material with momentjs

前端 未结 13 829
再見小時候
再見小時候 2020-11-28 09:01

Angular material introduced a new date picker component found here.

I want the date returned by this component to be in the format yyy-mm-dd but I am not su

13条回答
  •  星月不相逢
    2020-11-28 09:30

    For angular-material >= 5.x.x

    The recommended way of using other custom/predefined date formats is described in the angular material documentation:

    https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings

    An implementation example using MomentJS for customizing and parsing datetime display formats:

    ...
    import { MomentModule } from 'angular2-moment';
    
    import { MatMomentDateModule, MomentDateAdapter, MAT_MOMENT_DATE_FORMATS } from '@angular/material-moment-adapter';
    import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
    
    ...
    
    // moment formats explanation: https://momentjs.com/docs/#/displaying/format/
    export const MY_FORMATS = {
        parse: {
          dateInput: 'YYYY-MM-DD',
        },
        display: {
          dateInput: 'YYYY-MM-DD',
          monthYearLabel: 'MMM YYYY',
          dateA11yLabel: 'YYYY-MM-DD',
          monthYearA11yLabel: 'MMMM YYYY',
        },
      };
    
      ...
    
    @Component({
        ...
        providers: [
            // `MomentDateAdapter` and `MAT_MOMENT_DATE_FORMATS` can be automatically provided by importing
            // `MatMomentDateModule` in your applications root module. We provide it at the component level
            // here, due to limitations of our example generation script.
            {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
            // {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS},
            {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS}
        ]
    })
    
    ...
    

    Depending on your implementation, inside the component you might also need to use:

    date = new FormControl(moment());

    You must also install Moment library and adapter for Angular:

    https://www.npmjs.com/package/angular2-moment

    npm install --save angular2-moment

    https://www.npmjs.com/package/@angular/material-moment-adapter

    npm install --save @angular/material-moment-adapter

提交回复
热议问题