To format the date with a specific format, but still want to keep the internationalization behavior (like displaying month label in the datepicker control):
NativeDateAdapter
, override the format
function but still reuse the base _format
function public override format(date: Date, displayFormat: Object): string {
if (!date) {
return '';
}
// We want to display the same format `dd.MM.yyyy` for all locales in the application
// Thus, we use 'de-CH' locale for all cases
const dtf = new Intl.DateTimeFormat('de-CH', { ...displayFormat, timeZone: 'utc' });
return this.nativeFormat(dtf, date);
}
// This function is exactly the same as the function `_format` of the parent class `NativeDateAdapter`
private nativeFormat(dtf: Intl.DateTimeFormat, date: Date) {
// Passing the year to the constructor causes year numbers <100 to be converted to 19xx.
// To work around this we use `setUTCFullYear` and `setUTCHours` instead.
const d = new Date();
d.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate());
d.setUTCHours(date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
return dtf.format(d);
}
MAT_DATE_FORMATS
to use 2-digit
for monthconst appDateFormat: MatDateFormats = Object.freeze({
parse: {
dateInput: null,
timeInput: null,
},
display: {
dateInput: { year: 'numeric', month: '2-digit', day: '2-digit' },
timeInput: { hour: '2-digit', minute: '2-digit' },
monthYearLabel: { year: 'numeric', month: '2-digit' },
dateA11yLabel: { year: 'numeric', month: '2-digit', day: '2-digit' },
monthYearA11yLabel: { year: 'numeric', month: '2-digit' },
timeOptionLabel: { hour: '2-digit', minute: '2-digit' },
},
});
Check this article for more details on how the Angular Material Datepicker works.