Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material 5 - How to Customise date in mat-datepicker

How do I customise mat-datepicker date in MM/DD/YYYY format?

I'm using following following configuration:

HTML:

<mat-form-field>
  <input matInput [matDatepicker]="picker" placeholder="Choose a date">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

TS:

import {Component} from '@angular/core';

/** @title Basic datepicker */
@Component({
  selector: 'datepicker-overview-example',
  templateUrl: 'datepicker-overview-example.html',
  styleUrls: ['datepicker-overview-example.css'],
})
export class DatepickerOverviewExample {}

When I print the form value it gives me following output:

Sun Dec 31 2017 00:00:00 GMT+0530 (IST)

I'm expecting format in MM/DD/YYYY.

I tried this configuration: https://material.angular.io/components/datepicker/overview#customizing-the-parse-and-display-formats

But it didn't work for me. I'm using default MatNativeDateModule (Not moment js)

like image 673
Sahil Purav Avatar asked Dec 31 '17 16:12

Sahil Purav


2 Answers

The below code will format the date of all date pickers in your angular application.

Create a constant for date format.

export const DateFormat = {
 parse: {
 dateInput: 'input',
 },
display: {
dateInput: 'MM/DD/YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'MM/DD/YYYY',
monthYearA11yLabel: 'MMMM YYYY',
}
};

And Use the below code inside app module

providers: [
  { provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
  { provide: MAT_DATE_FORMATS, useValue: DateFormat }
 ]
like image 105
Mohan Singh Avatar answered Nov 05 '22 23:11

Mohan Singh


You can use the Date Pipe as follows,

<input mdInput placeholder="Title" [ngModel]="mydate  | date:'MM-dd-yyyy'">

DEMO

like image 10
Sajeetharan Avatar answered Nov 05 '22 23:11

Sajeetharan