Sometimes, we want to set the Material date picker date format with Angular and TypeScript.
In this article, we’ll look at how to set the Material date picker date format with Angular and TypeScript.
How to set the Material date picker date format with Angular and TypeScript?
To set the Material date picker date format with Angular and TypeScript, we create a custom date adapter.
For instance, we write
const MY_DATE_FORMATS = {
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" },
},
};
to define a constant with the date formats.
Then we write
export class MyDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === "input") {
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return this._to2digit(day) + "/" + this._to2digit(month) + "/" + year;
} else {
return date.toDateString();
}
}
private _to2digit(n: number) {
return ("00" + n).slice(-2);
}
}
to return the date string in the format we want.
Then we write
//...
@NgModule({
//...
providers: [
{ provide: DateAdapter, useClass: MyDateAdapter },
{ provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS },
],
//...
})
export class AppModule {}
to add the adapter class and the object to our module.
Conclusion
To set the Material date picker date format with Angular and TypeScript, we create a custom date adapter.