[Angular Material: DatePicker] Set Custom Date in (DD-MM-YYYY) format

Amandeep Kochhar
2 min readJun 5, 2019

--

As working with Angular Material 8 DatePicker Component, i was not able to set the Date in a specific format. After spending 2 hours of researching, i achieved the Goal by following multiple articles. Later thought why don’t i make it easy for others, who might get into the same situation.

So here i am, Back with another problem solving magical thing, Here i was using Template-Driven Approach to build forms.

The HTML CODE

<mat-form-field><input matInput placeholder=”Select Date” [matDatepicker]=”datepickerRef” name=”datepicker” ngModel #dateCtrl=”ngModel” required readonly/><mat-datepicker-toggle [for]=”datepickerRef” matSuffix></mat-datepicker-toggle><mat-datepicker #datepickerRef></mat-datepicker>
<mat-error *ngIf=”dateCtrl.errors?.required && deptCtrl.touched”>Choose a Date</mat-error>
</mat-form-field>

The HELPER Function

This is the functionthat will translate the Date to DD-MM-YYYY format as the example, however you can customize it accordingly. I created a single file named “format-datepicker.ts” and written following code..

import { NativeDateAdapter } from ‘@angular/material’;
import { MatDateFormats } from ‘@angular/material/core’;
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === ‘input’) {
let day: string = date.getDate().toString();
day = +day < 10 ? ‘0’ + day : day;
let month: string = (date.getMonth() + 1).toString();
month = +month < 10 ? ‘0’ + month : month;
let year = date.getFullYear();
return `${day}-${month}-${year}`;
}
return date.toDateString();
}
}
export const APP_DATE_FORMATS: MatDateFormats = {
parse: {
dateInput: { month: ‘short’, year: ‘numeric’, day: ‘numeric’ },
},
display: {
dateInput: ‘input’,
monthYearLabel: { year: ‘numeric’, month: ‘numeric’ },
dateA11yLabel: { year: ‘numeric’, month: ‘long’, day: ‘numeric’
},
monthYearA11yLabel: { year: ‘numeric’, month: ‘long’ },
}
};

Provide this implementation inside the providers tag of Component Decorator by overriding the default,

import {DateAdapter, MAT_DATE_FORMATS} from '@angular/material/core';
import { AppDateAdapter, APP_DATE_FORMATS } from 'src/app/shared/format-datepicker';
@Component({
selector: ‘app-create-employee’,
templateUrl: ‘./create-employee.component.html’,
styleUrls: [‘./create-employee.component.css’],
providers: [
{provide: DateAdapter, useClass: AppDateAdapter},
{provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}
]
})

And Boom, You will see the result!

Leave a few claps, if this article helped you in any way :)

--

--

Responses (19)