Set date format for datepicker material in angular 2

I am new to 'angular2' and 'angular js material'. In my project I use file-datepicker.

This is my date picker

<material-datepicker placeholder="Select Date" [(date)]="currentDate" name="currentDate" required></material-datepicker>

It will be displayed in the browser as shown below.

enter image description here

I'm concerned about the date issue. How to set the date format from 2017/04/27 to April 27, 2017.

+4
source share
3 answers

You can use dateFormat, and specify tags MMMM DD YYYY, where:

  • MMMM - month name
  • DD - day of the month.
  • YYYY - year

as stated in momentjs docs .

Your code will look like this:

<material-datepicker [dateFormat]="'MMMM DD YYYY'" placeholder="Select Date" [(date)]="currentDate" name="currentDate" required></material-datepicker>
0
source

, , , , , . [dateFormat]="'LL'"

0

In angular 2 for md datepicker you can change the date format as below:

Create a component that extends the NativeDateAdapter:

import { Component, OnInit } from '@angular/core';
import { NativeDateAdapter } from '@angular/material';
export class DateAdapterComponent extends NativeDateAdapter {
    format(date: Date, displayFormat: Object): string {
        let day = date.getDate();
        let month = date.getMonth();
        let year = date.getFullYear();

        if (displayFormat == "input") { 
            return this._toString(month) + ' '+ this._to2digit(day) + ',' + year;
        } else {
            return this._toString(month) + ' ' + year;
        }
    }

    private _to2digit(n: number) {
        return ('00' + n).slice(-2);
    } 

    private _toString(n: number) {
        let month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        return month[n];
    } 
}

Add the date format constant to the application module:

const MY_DATE_FORMATS:MdDateFormats = {
    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'},
    }
};

and in the provider, add a date adapter and date format:

  providers: [ {provide: DateAdapter, useClass: DateAdapterComponent},
               {provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS}],
0
source

Source: https://habr.com/ru/post/1675777/


All Articles