Angular 2 Material 2 datepicker date format

前端 未结 14 2300
悲哀的现实
悲哀的现实 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:42

    Why to not use Angular DatePipe?

    import {Component} from '@angular/core';
    import {DateAdapter, MAT_DATE_FORMATS, NativeDateAdapter} from '@angular/material';
    import {FormControl} from '@angular/forms';
    import {DatePipe} from '@angular/common';
    
    export const PICK_FORMATS = {
        parse: {dateInput: {month: 'short', year: 'numeric', day: 'numeric'}},
        display: {
            dateInput: 'input',
            monthYearLabel: {year: 'numeric', month: 'short'},
            dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
            monthYearA11yLabel: {year: 'numeric', month: 'long'}
        }
    };
    class PickDateAdapter extends NativeDateAdapter {
        format(date: Date, displayFormat: Object): string {
            if (displayFormat === 'input') {
                return new DatePipe('en-US').transform(date, 'EEE, MMM dd, yyyy');
            } else {
                return date.toDateString();
            }
        }
    }
    @Component({
        selector: 'custom-date',
        template: `
                       
                       
                       
                   `,
        providers: [
            {provide: DateAdapter, useClass: PickDateAdapter},
            {provide: MAT_DATE_FORMATS, useValue: PICK_FORMATS}
        ]
    })
    export class DateComponent {
        date = new FormControl(new Date());
        constructor() {}
    }
    

提交回复
热议问题