[Due for payment 2026-12-08] [$175] [Sentry: APP-NY2 / APP-NK1] iOS Insights crashes with “Invalid time value”
Insights can crash during date-control rendering on iOS HybridApp.
Evidence
- APP-NY2: 8 events / 6 users; all recorded events were simulator builds.
- APP-NK1: matching stack, 118 events / 37 users. Production confirmed on App Store build 9.5.23.3 with
device.simulator=false. - Stack:
InsightsDateControl → getDateDisplayValue → formatToReadableString → date-fns format. - The formatter parses
yyyy-MM-ddand formats without validating the result. The offending value and its source remain unconfirmed.
Expected: Insights renders without crashing; unsupported date selections are handled safely.
Actual: Unhandled RangeError: Invalid time value interrupts rendering.
Reproduction: Exact steps are not yet established.
Testing: Identify the triggering value, add regression coverage, and verify Insights date presets, custom dates, and restored selections on iOS.
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022119255195107030996
- Upwork Job ID: 2119255195107030996
- Last Price Increase: 2026-11-08
Issue Owner
Current Issue Owner: @FitseTLT
Triggered auto assignment to Contributor-plus team member for initial proposal review - @FitseTLT (External)
Job added to Upwork: https://www.upwork.com/jobs/~022119255195107030996
🤖 Web test steps verification results: ⚠️ partial
Dev NewDot web onboarding completed, but Insights date controls were inaccessible. No iOS verification performed.

| Step | Status |
|---|---|
Date presets render without Invalid time valueBlocked: Insights displayed an expense-empty state without date controls; overlapping dialogs prevented expense setup.Preliminary analysis — low confidence in the production trigger. The reported exception has a clear conditional mechanism: a nonempty, unrecognized date value reaches date-fns parsing, and formatting the resulting invalid date throws. However, neither the actual offending value nor its producer was established. Supporting code: restored non-preset dates are accepted without validation in insightsFilterParsing.ts:23–38. The display helper forwards them to formatting in SearchUIUtils.ts:6411–6438, which formats the parsed date without checking validity in DateUtils.ts:1155–1161. Hypothesis challenged: merely selecting a preset omitted from the Insights picker does not explain this failure. Recognition covers every defined preset, not just those offered by the picker (SearchQueryUtils.ts:1093–1102). No supported picker flow producing malformed input was identified. Next investigation: obtain the affected event’s exact date value and source-mapped release context. Production-event access was unavailable, and equivalence between the inspected commit and release 9.5.23.3 remains unverified. Validating restored dates and testing malformed selections are reasonable resilience measures, but are not yet a verified solution to this incident. ![]() |
❌ |
Valid custom date/range rendersNot verified: date controls were not reached. This does not demonstrate a custom-date failure. |
❌ |
Reload safely restores date selectionNot attempted: session constraints prohibited reloading because authentication could be lost. Restored-selection behavior remains unverified. |
❌ |
Proposal
What is the root cause of that problem?
In src/libs/DateUtils.ts:1155–1158, formatToReadableString parses an incoming date string and immediately formats it without validating whether the parsed result is a valid date:
const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
};
When date is not in strict yyyy-MM-dd format (e.g. malformed query string, ISO timestamp, non-standard date format, or empty/corrupt stored filter value), parse(date, 'yyyy-MM-dd', new Date()) returns an Invalid Date object (new Date(NaN)).
In date-fns, passing an Invalid Date to format(parsedDate, ...) throws:
RangeError: Invalid time value
In InsightsDateControl.tsx:44–46:
<DropdownButton
label={label}
value={getDateDisplayValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, buildDateFormValues(value), translate, dateFnsLocale)}
...
/>
getDateDisplayValue calls DateUtils.formatToReadableString(on, dateFnsLocale). Because this runs synchronously inside the component render pass, the unhandled RangeError: Invalid time value immediately crashes the screen.
Furthermore, in src/pages/Insights/insightsFilterParsing.ts:20–35, parseDate extracts equality date filters from search queries. When a custom date value is present in onValue, it checks isSearchDatePreset(on), but if not a preset, it unconditionally sets {date: {on}} without verifying that on represents a parseable, valid date.
What changes do you think we should make in order to solve the problem?
-
Harden
formatToReadableStringinsrc/libs/DateUtils.ts:1155–1158: Add validation usingisValid(parsedDate)(already imported fromdate-fnson line 35). Also add fallback parsing viaparseISO(date)to safely support ISO strings, and fallback to returning the raw date or empty string instead of throwing an unhandled exception:/** * Converts a date to a string in the format MMMM d, yyyy */ const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => { if (!date) { return ''; } const parsedDate = parse(date, 'yyyy-MM-dd', new Date()); if (isValid(parsedDate)) { return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale}); } const isoDate = parseISO(date); if (isValid(isoDate)) { return format(isoDate, 'MMMM d, yyyy', {locale: dateFnsLocale}); } return date; }; -
Validate custom dates in
src/pages/Insights/insightsFilterParsing.ts:24–30: InparseDate, verify that customondate values represent valid dates before constructing{date: {on}}. If invalid, returnundefinedso that the dashboard safely falls back to default preset selections:const onValue = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString(); if (onValue) { const on = normalizeDatePreset(onValue); if (isSearchDatePreset(on)) { return {date: {preset: on}}; } const parsed = parse(on, 'yyyy-MM-dd', new Date()); if (isValid(parsed) || isValid(parseISO(on))) { return {date: {on}}; } return undefined; } -
Add unit test coverage in
tests/unit/DateUtilsTest.ts: Add tests verifying thatDateUtils.formatToReadableString:- Correctly formats valid
yyyy-MM-dddate strings (e.g.'2026-11-08'->'November 8, 2026'). - Correctly formats ISO date strings (e.g.
'2026-11-08T00:00:00.000Z'). - Gracefully returns empty string when given empty/falsy inputs without throwing.
- Gracefully returns the raw string without throwing
RangeError: Invalid time valuewhen given invalid date strings (e.g.'invalid-date','not-a-date').
- Correctly formats valid
What alternative solutions did you explore? (Optional)
- Wrapping only
InsightsDateControlin try/catch: Rejected becausegetDateDisplayValueinSearchUIUtils.tsis shared across Search and Insights filters. HardeningDateUtils.formatToReadableStringaddresses the root defect across all current and future consumers.
Tests
- Insights Date Control:
- Open Insights dashboard on iOS HybridApp, Web, or Android.
- Test date presets (e.g. "Year to date", "Last 30 days", "All time").
- Test custom single date selection ("On [date]").
- Verify Insights renders without crashing and displays the formatted date cleanly.
- Invalid Date Value Resilience:
- Navigate to an Insights URL with an invalid date parameter (e.g.
?date=invalidor?date=2026-99-99). - Verify the screen does not crash with
RangeError: Invalid time valueand safely defaults to valid date rendering.
- Navigate to an Insights URL with an invalid date parameter (e.g.
- Unit Tests:
- Run
npm test tests/unit/DateUtilsTest.tsand verify all tests pass.
- Run
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS HybridApp (and any platform when restoring or evaluating Insights filters), rendering InsightsDateControl crashes with an unhandled RangeError: Invalid time value inside InsightsDateControl → getDateDisplayValue → formatToReadableString → date-fns format.
What is the root cause of that problem?
There are three unvalidated hops in the Insights date-filter parsing and display pipeline where non-yyyy-MM-dd or invalid date values bypass validation (unlike buildFilterFormValuesFromQuery in src/libs/SearchQueryUtils.ts:2155-2177):
-
parseDateinsrc/pages/Insights/insightsFilterParsing.ts(lines 23–39) accepts any rawdate:,date>=, ordate<=token fromONYXKEYS.SEARCH_FILTERSwithout callingisValidDateor checking preset eligibility:function parseDate(queryJSON: SearchQueryJSON): Pick<InsightsFilters, 'date'> | undefined { const dateFilters = queryJSON.flatFilters.filter(({key}) => key === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE).flatMap(({filters}) => filters); const onValue = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString(); if (onValue) { const on = normalizeDatePreset(onValue); return {date: isSearchDatePreset(on) ? {preset: on} : {on}}; } const from = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO)?.value.toString(); const to = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO)?.value.toString(); if (from && to) { return {date: {from, to}}; } return undefined; }- Compare this with
buildFilterFormValuesFromQueryinsrc/libs/SearchQueryUtils.ts(lines 2157–2166), which explicitly validates every date filter token withisValidDate(filter.value.toString()) || isSearchDatePreset(filter.value.toString()):const rangeStartFilter = filterList.find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO && isValidDate(filter.value.toString())); const rangeEndFilter = filterList.find((filter) => filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO && isValidDate(filter.value.toString())); const onFilter = filterList.find((filter) => { return filter.operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO && (isValidDate(filter.value.toString()) || isSearchDatePreset(filter.value.toString())); }); - Because
parseDateomitsisValidDate:- Any non-preset
date:value stored innvp_searchFilters.insightsSpend.queryorinsightsCompliance.query(e.g. a legacy/unindexed preset or non-yyyy-MM-ddstring whereisSearchDatePreset(on)isfalse) is returned as{on}, whichbuildDateFormValues(src/pages/Insights/insightsQueries.ts:24-26) turns into{dateOn: on}. - Even if a preset is recognized by
isSearchDatePreset(such asCONST.SEARCH.DATE_PRESETS.NEVERorLAST_STATEMENT),InsightsDateControl(src/pages/Insights/controls/InsightsDateControl.tsx:23) only allowsgetDatePresets(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, false)(which excludesneverandlast-statement), yetparseDatestill accepts them. - Similarly, for
date>=anddate<=,parseDatedoes not checkisValidDate(from) && isValidDate(to) && from <= to.
- Any non-preset
- Compare this with
-
fromSearchDateValuesinsrc/pages/Insights/insightsFilterParsing.ts(lines 91–103) also omitsisValidDate(on):const on = values[CONST.SEARCH.DATE_MODIFIERS.ON]; if (!on) { return undefined; } return isSearchDatePreset(on) ? {preset: on} : {on};Whereas the range branch on line 92 uses
getRangeBoundariesFromFormValue, which validatesisValidDate(rawFrom)andisValidDate(rawTo)insideparseRangeQueryValue(src/libs/SearchQueryUtils.ts:588-589), theONbranch accepts any non-preset string without checkingisValidDate(on)or verifying that a preset is supported by Insights (INSIGHTS_DATE_PRESETS). -
getDateDisplayValue(src/libs/SearchUIUtils.ts:6411-6439) andDateUtils.formatToReadableString(src/libs/DateUtils.ts:1158-1161) calldate-fnsformatwithout validating the parsedDate: Insrc/libs/SearchUIUtils.ts:6419-6429:if (on) { parts.push(isSearchDatePreset(on) ? translate(`search.filters.date.presets.${on}`) : `${translate('common.on')} ${DateUtils.formatToReadableString(on, dateFnsLocale)}`); }And in
src/libs/DateUtils.ts:1158-1161:const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => { const parsedDate = parse(date, 'yyyy-MM-dd', new Date()); return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale}); };When
on(orafter/before) is not a validyyyy-MM-dddate string,parse(date, 'yyyy-MM-dd', new Date())returns anInvalid Date(NaN), andformat(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale})immediately throwsRangeError: Invalid time value, crashingInsightsDateControlduring render!
What changes do you think we should make in order to solve the problem?
We should validate date selections at the Insights filter parsing boundary (src/pages/Insights/insightsFilterParsing.ts) so unsupported/invalid dates fall back cleanly to DEFAULT_INSIGHTS_FILTERS.date, AND harden DateUtils.formatToReadableString / getDateDisplayValue so invalid date strings never throw a RangeError during render:
-
Validate presets and
yyyy-MM-dddates insrc/pages/Insights/insightsFilterParsing.ts(parseDateandfromSearchDateValues): ImportisValidDatefrom@libs/ValidationUtilsandgetDatePresetsfrom@libs/SearchUIUtils, and validate bothonandfrom/to:const INSIGHTS_VALID_DATE_PRESETS = new Set<string>(getDatePresets(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, false)); function isInsightsDatePreset(value: string | undefined): value is SearchDatePreset { return !!value && INSIGHTS_VALID_DATE_PRESETS.has(value) && isSearchDatePreset(value); } function parseDate(queryJSON: SearchQueryJSON): Pick<InsightsFilters, 'date'> | undefined { const dateFilters = queryJSON.flatFilters.filter(({key}) => key === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE).flatMap(({filters}) => filters); const onFilter = dateFilters.find(({operator, value}) => { if (operator !== CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO) { return false; } const normalized = normalizeDatePreset(value.toString()); return isInsightsDatePreset(normalized) || isValidDate(normalized); }); if (onFilter) { const on = normalizeDatePreset(onFilter.value.toString()); return {date: isInsightsDatePreset(on) ? {preset: on} : {on}}; } const from = dateFilters.find(({operator, value}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO && isValidDate(value.toString()))?.value.toString(); const to = dateFilters.find(({operator, value}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO && isValidDate(value.toString()))?.value.toString(); if (from && to && from <= to) { return {date: {from, to}}; } return undefined; }And in
fromSearchDateValues(lines 91–103):function fromSearchDateValues(values: SearchDateValues): InsightsFilters['date'] | undefined { const {from, to} = getRangeBoundariesFromFormValue(values[CONST.SEARCH.DATE_MODIFIERS.RANGE]); if (from && to && from <= to) { return {from, to}; } const rawOn = values[CONST.SEARCH.DATE_MODIFIERS.ON]; if (!rawOn) { return undefined; } const on = normalizeDatePreset(rawOn); if (isInsightsDatePreset(on)) { return {preset: on}; } if (isValidDate(on)) { return {on}; } return undefined; } -
Guard
formatToReadableStringinsrc/libs/DateUtils.ts(lines 1158–1161) andgetDateDisplayValueinsrc/libs/SearchUIUtils.ts(lines 6419–6430): Insrc/libs/DateUtils.ts:const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => { const parsedDate = parse(date, 'yyyy-MM-dd', new Date()); if (!isValid(parsedDate)) { return ''; } return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale}); };And in
src/libs/SearchUIUtils.ts(getDateDisplayValue), only push formattedon,after, andbeforeparts whenisSearchDatePreset(on)orDateUtils.formatToReadableString(...)returns a non-empty string:if (on) { if (isSearchDatePreset(on)) { parts.push(translate(`search.filters.date.presets.${on}`)); } else { const formattedOn = DateUtils.formatToReadableString(on, dateFnsLocale); if (formattedOn) { parts.push(`${translate('common.on')} ${formattedOn}`); } } } if (after) { const formattedAfter = DateUtils.formatToReadableString(after, dateFnsLocale); if (formattedAfter) { parts.push(`${translate('common.after')} ${formattedAfter}`); } } if (before) { const formattedBefore = DateUtils.formatToReadableString(before, dateFnsLocale); if (formattedBefore) { parts.push(`${translate('common.before')} ${formattedBefore}`); } } -
Add unit test coverage: Add unit tests in
tests/unit/InsightsFilterParsingTest.tsandtests/unit/SearchUIUtilsTest.tscovering:parseInsightsFilterswith valid presets (this-year,year-to-datenormalized tothis-year), validdate:2026-05-01, valid rangesdate>=2026-01-01 date<=2026-03-31, and invalid/unsupported stored dates (date:invalid,date:never, inverted rangesdate>=2026-05-01 date<=2026-01-01) falling back cleanly toundefinedsodefaultFilters.dateis used.getDateDisplayValueandDateUtils.formatToReadableStringreturning''instead of throwingRangeError: Invalid time valuewhen given a malformed date string.
What alternative solutions did you explore?
We considered only guarding DateUtils.formatToReadableString to return '' on invalid dates. However, if parseDate in insightsFilterParsing.ts still accepts an invalid or unsupported date token from a restored query in ONYXKEYS.SEARCH_FILTERS, filters.date would hold a broken {on: ...} object, causing InsightsDateControl to render an empty value label and getInsightsGroupByOptions / buildInsightsQueryString to query with a malformed date filter instead of falling back to DEFAULT_INSIGHTS_FILTERS.date (THIS_YEAR). Validating in both insightsFilterParsing.ts and DateUtils.formatToReadableString / getDateDisplayValue prevents both the crash and corrupted filter state.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS HybridApp (confirmed in production on App Store build 9.5.23.3 via Sentry APP-NK1 with 118 events / 37 users, and APP-NY2 on simulator builds), opening or rendering the Insights dashboard crashes with an unhandled RangeError: Invalid time value along the call stack InsightsDateControl → getDateDisplayValue → formatToReadableString → date-fns format.
What is the root cause of that problem?
-
Exact triggering value and source in production build
9.5.23.3(date:this-yearand newly added presets in server-syncedONYXKEYS.SEARCH_FILTERS):- In App Store build
9.5.23-3,CONST.SEARCH.DATE_PRESETSinsrc/CONST/index.tsonly contained 6 values (never,last-month,this-month,year-to-date,last-12-months,last-statement). - Subsequent commits on Web/NewDot (specifically PR
#104074/a4032aa21cand the expanded date presets insrc/CONST/index.ts) added 9 new presets (this-year,last-year,this-quarter,last-quarter,this-week,last-week,last-30-days,last-90-days,last-6-months) and changedDEFAULT_INSIGHTS_FILTERS.datefrom{preset: 'year-to-date'}to{preset: 'this-year'}. - Whenever a user opens Insights on Web (or a newer client),
getInsights/saveInsightsFilterspersists the dashboard filter query (e.g.groupBy:month groupCurrency:USD date:this-yearordate:last-30-days) into the server-synced NVPONYXKEYS.SEARCH_FILTERS(nvp_searchFilters.insightsSpend.query/nvp_searchFilters.insightsCompliance.query). - When that user opens the iOS HybridApp on
9.5.23.3(or whenevernvp_searchFilterscontains an unrecognized preset or malformeddate:value),parseDateinsrc/pages/Insights/insightsFilterParsing.ts:23-39runs:function parseDate(queryJSON: SearchQueryJSON): Pick<InsightsFilters, 'date'> | undefined { const dateFilters = queryJSON.flatFilters.filter(({key}) => key === CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE).flatMap(({filters}) => filters); const onValue = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString(); if (onValue) { const on = normalizeDatePreset(onValue); return {date: isSearchDatePreset(on) ? {preset: on} : {on}}; } const from = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.GREATER_THAN_OR_EQUAL_TO)?.value.toString(); const to = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.LOWER_THAN_OR_EQUAL_TO)?.value.toString(); if (from && to) { return {date: {from, to}}; } return undefined; } - Because
parseDatedoes not validateisValidDate(on)whenisSearchDatePreset(on)isfalse(unlikebuildFilterFormValuesFromQueryinsrc/libs/SearchQueryUtils.ts:2157-2165, which checksisValidDate(filter.value.toString()) || isSearchDatePreset(filter.value.toString())), any unrecognized preset or non-yyyy-MM-ddstring (such as'this-year'on9.5.23.3) is returned as a single-day filter{date: {on: 'this-year'}}.
- In App Store build
-
Unvalidated
from/toandfromSearchDateValuesinsrc/pages/Insights/insightsFilterParsing.ts:- In
parseDate(lines 32-36),fromandtoare also not validated withisValidDate(from) && isValidDate(to) && from <= to. - Furthermore,
parseDateandfromSearchDateValues(lines 91-103) checkisSearchDatePreset(on)rather than checking whether the preset is actually supported by Insights (INSIGHTS_DATE_PRESETS = getDatePresets(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, false)inInsightsDateControl.tsx:23, which excludesneverandlast-statement).
- In
-
Unvalidated
parse->formatinDateUtils.formatToReadableString(src/libs/DateUtils.ts:1158-1161):- When
InsightsDateControl(src/pages/Insights/controls/InsightsDateControl.tsx:45) callsgetDateDisplayValue(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, buildDateFormValues(value), translate, dateFnsLocale),getDateDisplayValue(src/libs/SearchUIUtils.ts:6419-6429) passesontoDateUtils.formatToReadableString(on, dateFnsLocale):const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => { const parsedDate = parse(date, 'yyyy-MM-dd', new Date()); return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale}); }; parse('this-year', 'yyyy-MM-dd', new Date())returns anInvalid Date(NaN), anddate-fnsformat(parsedDate, ...)immediately throwsRangeError: Invalid time valueduring render.
- When
What changes do you think we should make in order to solve the problem?
- Validate date presets and
yyyy-MM-ddcalendar dates insrc/pages/Insights/insightsFilterParsing.ts:- Check presets against the Insights-supported date presets (
getDatePresets(CONST.SEARCH.SYNTAX_FILTER_KEYS.DATE, false)) and validate custom single dates (on) and range bounds (from,to) withisValidDatefrom@libs/ValidationUtils. When a stored query contains an unsupported preset or invalid date string,parseDatereturnsundefinedsouseInsightsFilterscleanly falls back toDEFAULT_INSIGHTS_FILTERS.date({preset: CONST.SEARCH.DATE_PRESETS.THIS_YEAR}).
- Check presets against the Insights-supported date presets (
- Guard
formatToReadableStringinsrc/libs/DateUtils.tsandgetDateDisplayValueinsrc/libs/SearchUIUtils.ts:- Check
if (!isValid(parsedDate)) { return ''; }informatToReadableString(matchinggetSplitDateRangeDisplayValueright above it atDateUtils.ts:1145), and only appendon/after/beforelabels ingetDateDisplayValuewhenformatToReadableStringreturns a non-empty string.
- Check
- Add unit tests in
tests/unit/insightsFilterParsingTest.tsandtests/unit/DateUtilsTest.tscovering unrecognized presets, invalidyyyy-MM-ddstrings (e.g.date:invalid,date:2026-02-31), and inverted ranges.
What alternative solutions did you explore? (Optional)
- Only guarding
DateUtils.formatToReadableStringwithout validating ininsightsFilterParsing.ts: IfparseDatestill returns{date: {on: '<invalid>'}}for an unrecognized preset or malformed date token inONYXKEYS.SEARCH_FILTERS,InsightsDateControlwould render a blank label andgetInsightsGroupByOptions/buildInsightsQueryStringwould treat the invalid string as a single-day filter instead of falling back toDEFAULT_INSIGHTS_FILTERS.date(THIS_YEAR). Validating ininsightsFilterParsing.tsand guardingformatToReadableStringfixes both the crash and the filter fallback.
📣 @cocvn157! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:
- Make sure you've read and understood the contributing guidelines.
- Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
- Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
@MelvinBot can you create proposal for this issue?
Proposal
What is the root cause of that problem?
Insights accepts an unrecognized restored date token as a literal calendar date. Rendering then parses it as yyyy-MM-dd and formats the result without checking validity, which can throw RangeError: Invalid time value.
A cross-version preset mismatch is plausible: release 9.5.23-3 does not recognize this-year, while newer clients use it. However, the actual production input remains unconfirmed; this-year is a supported example of the failure mechanism, not a verified incident value.
Code evidence
- The reported release recognizes only six presets, excluding
this-year: CONST/index.ts:8981–8988. - Its restoration parser turns unknown tokens into literal dates: insightsFilterParsing.ts:12–18.
- Its formatter parses and formats without validation: DateUtils.ts:1077–1080.
- Current restoration still accepts genuinely unknown date tokens without validation: insightsFilterParsing.ts:23–38.
What changes do you think we should make in order to solve the problem?
- Validate incoming Insights dates. Preserve recognized presets and existing alias normalization. Accept literal dates and range boundaries only when the existing calendar-date validator accepts them.
- Use existing fallback behavior. Omit invalid restored date selections so the dashboard default applies, preserving other saved filters. Reject invalid picker values so the previous valid selection remains.
- Prevent rendering exceptions. Check the parsed date before formatting; return an empty display value when invalid. Only append “On”, “After”, or “Before” labels when formatting produced a value.
- Add regression coverage for unknown presets, impossible dates, invalid range boundaries, default restoration, and omission of dangling labels. Preserve valid dates, leap days, ranges, localized output, and recognized presets.
Implementation boundaries
- Existing default merging: useInsightsFilters.ts:38–44.
- Existing picker fallback: InsightsDateControl.tsx:29–35.
- Formatter guard: DateUtils.ts:1155–1161.
- Label handling: SearchUIUtils.ts:6411–6438.
What alternative solutions did you explore? (Optional)
- Formatter-only fallback: contains the exception but leaves an invalid filter in query state.
- Accept ISO timestamps or display raw input: broadens behavior without evidence that these are legitimate inputs.
- Restrict presets to picker options: unnecessary for this crash; recognized presets already bypass literal-date formatting.
Validation limitation: This is a defensive proposal for a source-supported failure path, not a confirmed correction of the production input’s source. Before treating it as the incident solution, capture the failing value and verify it against the affected release. No new runtime tests were performed for this proposal.
Next Steps for Contributor+ team:
To accept: After confirming the production trigger, use @MelvinBot implement [this](https://github.com/Expensify/App/issues/106314) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Proposal
What is the root cause of that problem?
src/libs/DateUtils.ts:1158-1161 — formatToReadableString parses with parse(date, 'yyyy-MM-dd', new Date()) and passes the result straight to format(), with no validity check:
const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
};
In date-fns, format() on an Invalid Date throws RangeError: Invalid time value.
The crash path is synchronous in render: src/pages/Insights/controls/InsightsDateControl.tsx renders getDateDisplayValue(...), and src/libs/SearchUIUtils.ts:6419-6420 calls DateUtils.formatToReadableString(on, dateFnsLocale) whenever on is not a recognised preset — so one bad value kills the whole Insights screen. The same unguarded call also serves the after and before values (SearchUIUtils.ts:6424, 6428).
The trigger the issue leaves unconfirmed is a stale value in a restored selection: src/pages/Insights/insightsFilterParsing.ts parseDate takes any non-preset on value from a stored dashboard query and keeps it as {date: {on}} with no validity check. normalizeDatePreset (src/libs/SearchQueryUtils.ts:1100-1102) only maps one deprecated preset ("Year to date" → "This year"), so any other legacy preset name — or a malformed date in a shared/bookmarked Insights URL — reaches on verbatim, and the next render throws. That matches the Sentry split: APP-NK1 is 118 events / 37 users on a production App Store build, i.e. real restored dashboards, not just simulator noise.
What changes do you think we should make in order to solve the problem?
-
Harden
formatToReadableStringinsrc/libs/DateUtils.ts:1158-1161(fixes every consumer at once, including theafter/beforepaths): return''for falsy input; ifisValid(parse(date, 'yyyy-MM-dd', new Date())), format it; else tryparseISO(date)and format if valid; else return the raw string instead of throwing.isValidandparseISOare already imported in this file (lines 35, 38). -
Validate in
parseDate(src/pages/Insights/insightsFilterParsing.ts): only store{date: {on}}whenonis a validyyyy-MM-dddate or a valid ISO date; otherwise drop the date filter so the dashboard falls back to its default preset instead of crashing on a restored selection. -
Add unit tests in
tests/unit/DateUtilsTest.ts: validyyyy-MM-ddformats correctly; ISO strings format correctly; empty input returns''without throwing; invalid strings ('invalid-date','2026-99-99') and a stale preset name return the raw string without throwing. Plus a parsing test: a stored Insights query carrying an unparseableonvalue yields no date filter.
Tests
- Insights Date Control: open the Insights dashboard on iOS HybridApp, Web, and Android. Test date presets, a custom single ("On") date, and a restored dashboard whose saved query carries a stale preset value. Verify Insights renders without crashing and the date displays cleanly.
- Invalid Date Value Resilience: navigate to an Insights URL with an invalid date parameter (e.g.
?date=invalid,?date=2026-99-99). Verify the screen does not crash and safely falls back to the default preset. - Unit Tests: run
npm test tests/unit/DateUtilsTest.tsand verify all tests pass.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS HybridApp (and across all platforms when rendering Insights or Search date controls with restored or cross-version date filters), the app crashes during render with an unhandled exception:
RangeError: Invalid time value
Stack trace:
InsightsDateControl → getDateDisplayValue → formatToReadableString → date-fns format
Confirmed via Sentry issues APP-NY2 (simulator) and APP-NK1 (production App Store build 9.5.23.3 with 118 events across 37 users).
What is the root cause of that problem?
The crash is caused by an unvalidated parse-and-format chain combined with permissive date filter restoration:
-
Unchecked
date-fns/formatexecution insrc/libs/DateUtils.ts:1062-1065:const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => { const parsedDate = parse(date, 'yyyy-MM-dd', new Date()); return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale}); };parse(date, 'yyyy-MM-dd', new Date())fromdate-fnsdoes not throw when provided with an invalid or unexpected string (such as an unrecognized preset token, a datetime string with timestamps, or malformed user input). Instead, it returns anInvalid Dateobject whose time value isNaN.format(parsedDate, ...)is called directly without verifying whetherparsedDateis valid.date-fns/formatthrowsRangeError: Invalid time valuewhen called on an invalid date, unceremoniously crashing the React render tree. -
Permissive date token classification in
src/pages/Insights/insightsFilterParsing.ts:14-17:const on = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString(); if (on) { return {date: isSearchDatePreset(on) ? {preset: on} : {on}}; }If a restored, deep-linked, or cross-version query contains an
onvalue that is not recognized by the current version'sisSearchDatePreset(or contains malformed text),parseDateassumes it must be a literal date and packages it as{on}. This is then passed togetDateDisplayValueinSearchUIUtils.ts:5743:parts.push(isSearchDatePreset(on) ? translate(`search.filters.date.presets.${on}`) : `${translate('common.on')} ${DateUtils.formatToReadableString(on, dateFnsLocale)}`);This immediately passes the invalid string into
formatToReadableString, crashingInsightsDateControl.
What changes do you think we should make in order to solve the problem?
-
Defensively validate parsed dates in
src/libs/DateUtils.ts: ImportisValidfromdate-fnsand verify the parsed date before formatting:--- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -1,7 +1,7 @@ import { addDays, addHours, + isValid, parse, format, ... @@ -1062,4 +1062,8 @@ const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => { + if (!date) { + return ''; + } const parsedDate = parse(date, 'yyyy-MM-dd', new Date()); + if (!isValid(parsedDate)) { + return date; + } return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale}); };If parsing yields an invalid date,
formatToReadableStringsafely returns the raw stringdaterather than throwingRangeError: Invalid time value. This protects all callers across the app (includingInsightsDateControl,SearchUIUtils, andCardUtils). -
Validate literal calendar dates in
src/pages/Insights/insightsFilterParsing.ts: Ensureon,from, andtoare valid calendar dates before treating them as custom date filters:--- a/src/pages/Insights/insightsFilterParsing.ts +++ b/src/pages/Insights/insightsFilterParsing.ts @@ -14,6 +14,12 @@ function parseDate(queryJSON: SearchQueryJSON): Pick<InsightsFilters, 'date'> | const on = dateFilters.find(({operator}) => operator === CONST.SEARCH.SYNTAX_OPERATORS.EQUAL_TO)?.value.toString(); if (on) { - return {date: isSearchDatePreset(on) ? {preset: on} : {on}}; + if (isSearchDatePreset(on)) { + return {date: {preset: on}}; + } + const parsed = parse(on, 'yyyy-MM-dd', new Date()); + if (isValid(parsed) && CONST.DATE.REGEX.DATE.test(on)) { + return {date: {on}}; + } + return undefined; }This prevents unknown or corrupted date tokens from masquerading as custom dates in filter state.
What alternative solutions did you explore? (Optional)
- Wrapping
formatin atry...catchblock insideformatToReadableString: While atry...catchprevents unhandled crashes, explicitisValid(parsedDate)checking is faster, idiomatic fordate-fns, and avoids relying on exception handling for standard input validation. - Only fixing
insightsFilterParsing.ts: Rejected becauseformatToReadableStringis a public utility inDateUtils.tsused by multiple features (such asCardUtils.tsandSearchUIUtils.ts). A utility that crashes the UI when given unexpected input represents an architectural liability that must be hardened at the source.
What automated tests can you add to prevent this from re-occurring?
In tests/unit/DateUtilsTest.ts:
- Verify
DateUtils.formatToReadableStringreturns formatted date for validyyyy-MM-dd. - Verify
DateUtils.formatToReadableStringreturns the input string without throwing for invalid inputs (e.g.'invalid-date','last-month','2024-13-45','').
In tests/unit/insightsFilterParsingTest.ts:
- Verify
parseDatecorrectly parses valid presets (this-month), valid calendar dates (2026-11-08), and safely handles/rejects corrupted or unrecognized tokens without crashing.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0105126232377c4c5c
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0114a7a02ed80f61b6
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS HybridApp (as tracked by Sentry issues APP-NY2 and APP-NK1), opening Insights crashes with an unhandled exception: RangeError: Invalid time value.
What is the root cause of that problem?
In src/libs/DateUtils.ts, formatToReadableString formats a date string using:
const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => {
const parsedDate = parse(date, 'yyyy-MM-dd', new Date());
return format(parsedDate, 'MMMM d, yyyy', {locale: dateFnsLocale});
};
- When
dateis undefined, empty, or not in validyyyy-MM-ddcalendar format,date-fns/parsereturns an invalid Date object (isNaN(parsedDate.getTime())). - Calling
date-fns/format(parsedDate, ...)with an invalid Date object immediately throwsRangeError: Invalid time value. - In
src/pages/Insights/insightsFilterParsing.ts(parseDate), if anon,from, ortodate parameter inqueryJSONis not recognized as a preset byisSearchDatePreset(), it is packaged as{date: {on}}without verifying whether it is a valid calendar date format. - When
InsightsDateControlpasses this unvalidated string throughgetDateDisplayValueinSearchUIUtils.tstoDateUtils.formatToReadableString(), the unhandledRangeErrorcrashes the component during rendering on iOS.
What changes do you think we should make in order to solve the problem?
-
Defensively harden
formatToReadableStringinsrc/libs/DateUtils.ts: ImportisValidfromdate-fnsand validateparsedDatebefore formatting:const formatToReadableString = (date: string, dateFnsLocale: DateFnsLocale | undefined): string => { if (!date) { return ''; } const parsedDate = parse(date, CONST.DATE.FNS_FORMAT_STRING, new Date()); if (!isValid(parsedDate)) { return date; } return format(parsedDate, CONST.DATE.MONTH_DAY_YEAR_FORMAT, {locale: dateFnsLocale}); };If parsing fails or produces an invalid date,
formatToReadableStringsafely returns the raw stringdaterather than throwing an unhandledRangeError: Invalid time value. This protects all callers across the app (includingInsightsDateControl,SearchUIUtils, andCardUtils). -
Validate calendar date strings in
src/pages/Insights/insightsFilterParsing.ts: InparseDate(), ensure non-preseton,from, andtovalues conform to a valid calendar date (e.g. matchingCONST.DATE.REGEX.DATEandisValid(parse(val, 'yyyy-MM-dd', new Date()))) before returning them in the filter state. Corrupted or unsupported date values will be safely ignored rather than causing malformed state.
What alternative solutions did you explore? (Optional)
- Wrapping
formatin atry...catchblock informatToReadableString: While atry...catchavoids the unhandled crash, explicitisValid(parsedDate)checking is faster, idiomatic fordate-fns, and avoids exception handling overhead during component rendering. - Only validating inside
insightsFilterParsing.ts: Rejected becauseformatToReadableStringis a public utility inDateUtils.tsused by multiple features. HardeningDateUtils.formatToReadableStringat the source prevents similar unhandled Sentry crash spikes across the entire codebase.
What automated tests can you add to prevent this from re-occurring?
- In
tests/unit/DateUtilsTest.ts:- Verify
DateUtils.formatToReadableStringreturns formatted date for validyyyy-MM-dddates (e.g.,'2026-11-08'). - Verify
DateUtils.formatToReadableStringreturns the input string without throwingRangeErrorfor invalid inputs (e.g.,'invalid-date','last-month','2024-13-45','').
- Verify
- In
tests/unit/insightsFilterParsingTest.ts:- Verify
parseDatecorrectly extracts presets, valid calendar dates, and safely handles malformed or unknown date tokens without propagating invalid date state.
- Verify
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
On iOS HybridApp (and Simulator), navigating into or rendering the Insights date controls triggers an unhandled RangeError: Invalid time value fatal crash during date display calculation.
What is the root cause of that problem?
In InsightsDateControl (and related date-display helpers such as getDateDisplayValue / formatToReadableString), date strings parsed with date-fns are formatted directly via format(parsedDate, ...) without first validating isValid(parsedDate) or guarding against empty/unrecognized date string formats (e.g. malformed or partial ISO tokens restored from cached selections). When an invalid timestamp or non-ISO token reaches date-fns/format, date-fns throws an unhandled RangeError: Invalid time value, unmounting the component tree.
What changes do you think we should make in order to solve the problem?
- In
getDateDisplayValue(or the underlying date formatting utility), parse the input usingparseISO/new Date(value)and add an explicitisValid(parsedDate)validation guard. - If
!isValid(parsedDate), safely fallback to the current default date preset (or localized fallback string) instead of invokingformat(). - Add unit tests for
getDateDisplayValueverifying thatnull,undefined, empty string, and malformed date strings return the safe fallback without throwing aRangeError.
What alternative solutions did you explore? (Optional)
Wrapping the call in a local try/catch block. However, validating with isValid() from date-fns is cleaner, more idiomatic, and avoids relying on exception handling for standard input validation.
@MelvinBot raise pr then
🤖 Web test steps verification results: ❌ fail
Web verification was blocked by a blank page with no accessible controls. Date-safeguard behavior could not be verified in the browser; no iOS coverage was performed.

| Step | Status |
|---|---|
Insights presets render without Invalid time valueBlocked: snapshots returned no accessible controls; waiting for Insights timed out.![]() |
❌ |
Custom single date rendersBlocked: date controls were inaccessible. |
❌ |
Custom range rendersBlocked: date controls were inaccessible. |
❌ |
Created draft PR: Validate Insights dates and omit invalid date labels, assigned to FitseTLT, with PullerBear review requested.
Passed: 269 targeted tests, lint, type checking, Storybook smoke test, and coding-standards review. Full-suite testing timed out; formatting and final spelling verification remain incomplete. These limitations are documented in the draft.
view run · no recording available
PR under review
@FitseTLT Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!
Reviewing pr