79754680

Date: 2025-09-03 13:58:17
Score: 1
Natty:
Report link

To format the date with a specific format, but still want to keep the internationalization behavior (like displaying month label in the datepicker control):

  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);
  }
const 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.

Reasons:
  • Blacklisted phrase (1): this article
  • Contains signature (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: kal