Angular 2 Material 2 datepicker date format

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

    There's a high chance that you already use a library that provides you with an convinient way of manipulating (parsing, validating, displaying, etc.) dates and times in JavaScript. If you dont, take a look at one of them, for example moment.js.

    Implementing your custom adapter using moment.js would look like this.

    Create CustomDateAdapter.ts and implement it like this:

    import { NativeDateAdapter } from "@angular/material";
    import * as moment from 'moment';
    
    export class CustomDateAdapter extends NativeDateAdapter {
        format(date: Date, displayFormat: Object): string {
            moment.locale('ru-RU'); // Choose the locale
            var formatString = (displayFormat === 'input')? 'DD.MM.YYYY' : 'LLL';
            return moment(date).format(formatString);
        }
    }
    

    In your app.module.ts:

    import { DateAdapter } from '@angular/material';
    
    providers: [
        ...
        {
            provide: DateAdapter, useClass: CustomDateAdapter
        },
        ...
    ]
    

    That's it. Simple, easy and no need of reinventing bicycles.

提交回复
热议问题