Angular 2 Material 2 datepicker date format

前端 未结 14 2213
悲哀的现实
悲哀的现实 2020-11-28 23:21

I need help. I don\'t know how to change the date format of the material 2 datepicker. I\'ve read documentation but I don\'t understand what I actually need to do. Output da

相关标签:
14条回答
  • 2020-11-28 23:57

    You just need to provide a custom MAT_DATE_FORMATS

    export const APP_DATE_FORMATS = {
        parse: {dateInput: {month: 'short', year: 'numeric', day: 'numeric'}},
        display: {
            dateInput: {month: 'short', year: 'numeric', day: 'numeric'},
            monthYearLabel: {year: 'numeric'}
        }
    };
    

    and add it to providers.

    providers: [{
       provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
    }]
    

    Working code

    0 讨论(0)
  • 2020-11-29 00:01

    This is work for me!

    import {Component} from '@angular/core';
    import {FormControl} from '@angular/forms';
    import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
    import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
    
    // Depending on whether rollup is used, moment needs to be imported differently.
    // Since Moment.js doesn't have a default export, we normally need to import using the `* as`
    // syntax. However, rollup creates a synthetic default module and we thus need to import it using
    // the `default as` syntax.
    import * as _moment from 'moment';
    // tslint:disable-next-line:no-duplicate-imports
    import {default as _rollupMoment} from 'moment';
    
    const moment = _rollupMoment || _moment;
    
    // See the Moment.js docs for the meaning of these formats:
    // https://momentjs.com/docs/#/displaying/format/
    export const MY_FORMATS = {
    parse: {
        dateInput: 'LL',
    },
    display: {
        dateInput: 'LL',
        monthYearLabel: 'MMM YYYY',
        dateA11yLabel: 'LL',
        monthYearA11yLabel: 'MMMM YYYY',
    },
    };
    
    /** @title Datepicker with custom formats */
    @Component({
    selector: 'datepicker-formats-example',
    templateUrl: 'datepicker-formats-example.html',
    providers: [
        // `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
        // application's 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, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
        },
    
        {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
    ],
    })
    export class YourDatepickerUsedComponent {
        date = new FormControl(moment());
    }
    

    Link: https://material.angular.io/components/datepicker/examples and search "Datepicker with custom formats"

    0 讨论(0)
提交回复
热议问题