10
votes

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)

2
MatNativeDateModule store the date as a Date object. A Date object doesn't have any format. It's an object, wrapping a number of millis since 1970. But you can format it the way you want to, using the date pipe, for example.JB Nizet

2 Answers

10
votes

You can use the Date Pipe as follows,

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

DEMO

8
votes

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 }
 ]