{"record":{"id":"dcd629e9d2cfc240","repo":"angular/components","slug":"datefnsadapter-cannot-format-invalid-date","errorCode":null,"errorMessage":"DateFnsAdapter: Cannot format invalid date.","messagePattern":"DateFnsAdapter: Cannot format invalid date\\.","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/material-date-fns-adapter/adapter/date-fns-adapter.ts","lineNumber":168,"sourceCode":"    // Check that the date wasn't above the upper bound for the month, causing the month to overflow\n    if (result.getMonth() != month && (typeof ngDevMode === 'undefined' || ngDevMode)) {\n      throw Error(`Invalid date \"${date}\" for month with index \"${month}\".`);\n    }\n\n    return result;\n  }\n\n  today(): Date {\n    return new Date();\n  }\n\n  parse(value: unknown, parseFormat: string | string[]): Date | null {\n    return this._parse(value, parseFormat);\n  }\n\n  format(date: Date, displayFormat: string): string {\n    if (!this.isValid(date)) {\n      throw Error('DateFnsAdapter: Cannot format invalid date.');\n    }\n\n    return format(date, displayFormat, {locale: this.locale});\n  }\n\n  addCalendarYears(date: Date, years: number): Date {\n    return addYears(date, years);\n  }\n\n  addCalendarMonths(date: Date, months: number): Date {\n    return addMonths(date, months);\n  }\n\n  addCalendarDays(date: Date, days: number): Date {\n    return addDays(date, days);\n  }\n\n  toIso8601(date: Date): string {","sourceCodeStart":150,"sourceCodeEnd":186,"githubUrl":"https://github.com/angular/components/blob/0411926e7d8ae06b32236ec1048a888cfad5abf2/src/material-date-fns-adapter/adapter/date-fns-adapter.ts#L150-L186","documentation":"DateFnsAdapter.format refuses to format a Date that fails isValid (typically NaN time, i.e. an Invalid Date). date-fns' format would otherwise produce garbage like 'Invalid Date' strings; the adapter throws an explicit error instead so callers handle invalid dates deliberately.","triggerScenarios":"Calling format() (or getMonthNames/getDayOfWeekNames/getYearName paths that call it) with a Date created from invalid input — e.g. new Date('garbage'), a failed parse returning NaN, or arithmetic on invalid dates.","commonSituations":"Parsing user text that didn't match the expected format and passing the result straight to format; dates from external APIs that are null/undefined coerced to Invalid Date; date-fns version differences changing parse behavior.","solutions":["Check adapter.isValid(date) before calling format and handle the invalid branch.","Ensure parse() results are non-null before formatting.","Validate/sanitize date strings from user input or APIs before constructing Dates.","Use the adapter's today() or a fallback default date when parsing fails."],"exampleFix":"// before\nconst d = this.adapter.parse(input, 'yyyy-MM-dd');\nreturn this.adapter.format(d, 'dd/MM/yyyy'); // throws if d invalid\n// after\nconst d = this.adapter.parse(input, 'yyyy-MM-dd');\nreturn d && this.adapter.isValid(d) ? this.adapter.format(d, 'dd/MM/yyyy') : '';","handlingStrategy":"validation","validationCode":"if (!date || !adapter.isValid(date)) {\n  return ''; // or a fallback string\n}\nreturn adapter.format(date, displayFormat);","typeGuard":"function isAdapterValidDate(adapter: DateAdapter<Date>, d: unknown): d is Date {\n  return d instanceof Date && adapter.isValid(d);\n}","tryCatchPattern":"try {\n  return this.adapter.format(date, fmt);\n} catch (e) {\n  if ((e as Error).message.includes('Cannot format invalid date')) {\n    return ''; // or placeholder, or re-parse input\n  }\n  throw e;\n}","preventionTips":["Always check adapter.isValid after parse() before formatting","Reject null/NaN dates at API boundaries (forms, HTTP responses)","Wrap date parsing + formatting in one helper that handles the invalid branch once","Log invalid input values to surface upstream parse failures"],"tags":["date","validation","formatting","material","date-fns"],"backgroundTag":"invalid-date-argument","analyzedSha":"0411926e7d8ae06b32236ec1048a888cfad5abf2","analyzedAt":"2026-08-31T11:58:23.400Z","schemaVersion":2},"datasetVersion":"2026-08-31T14:17:45.589Z"}