matheo / angular

Open Source Angular Libraries: MatDataSource, MatDatepicker
http://matheo.co/demos/
MIT License
60 stars 15 forks source link

Support Multiple Time Formats #64

Open rohmann opened 2 years ago

rohmann commented 2 years ago

Angular Material allows multiple parse formats but the adapter only considers singular string values for the parseFormat.

Thought I'd mention it in case that's something that could be supported by the package internally, but was able to get around the issue by monkey patching in polyfills.ts

DateFnsAdapter.prototype.parse = function (
  value: any,
  parseFormat: string | string[]
): Date | null {
  if (value) {
    if (typeof value === 'string') {
      const parseFormats = Array.isArray(parseFormat)
        ? parseFormat
        : [parseFormat];
      const _value = value.trim();

      for (let format of parseFormats) {
        const d = parse(_value, format, new Date(), {
          locale: this._dateFnsLocale,
        });

        if (d && d.toString() !== 'Invalid Date') {
          return this.options.useUtc ? zonedTimeToUtc(d, 'UTC') : d;
        }
      }

      return new Date(value);
    }
    if (typeof value === 'number') {
      return toDate(value);
    }
    if (value instanceof Date) {
      return this.clone(value as Date);
    }
    return value;
  }
  return value;
};
rohmann commented 2 years ago

Updated the example. Needed to stop returning null to allow form validation errors to show up since null was an acceptable value.