Skip to content

Support Multiple Time Formats #64

@rohmann

Description

@rohmann

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;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions