From c0affab7f0fd0641da13112ed8208fde69598654 Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Wed, 4 Nov 2026 13:25:28 +0530 Subject: [PATCH 1/4] Localize abbreviated month and day dates Add DateUtils.formatToMonthDay, backed by a cached Intl.DateTimeFormat, and formatToMonthDayWithOptionalYearInUTC, which keeps the past-year rule and reads calendar dates as UTC. Search rows, transaction previews, recently added expenses, split rows, the card authorization preview, calendar times this week and the reusable route Last used date now use them, so other languages get their own month-day order. English output is unchanged. --- .../Search/SearchList/ListItem/DateCell.tsx | 8 +-- .../ListItem/WithdrawalIDListItemHeader.tsx | 6 +- .../getExpenseReportRowDisplayValues.ts | 8 +-- src/libs/DateUtils.ts | 39 ++++++++++- src/libs/ReusableDistanceRoutesUtils.ts | 8 ++- src/libs/TransactionPreviewUtils.ts | 6 +- .../AuthorizeCardTransactionPreview.tsx | 4 +- .../RecentlyAddedSection/RecentlyAddedRow.tsx | 6 +- src/pages/iou/DynamicSplitExpensePage.tsx | 6 +- .../iou/request/step/ReuseRouteListItem.tsx | 4 +- tests/unit/DateUtilsMonthDayTest.ts | 68 +++++++++++++++++++ 11 files changed, 121 insertions(+), 42 deletions(-) create mode 100644 tests/unit/DateUtilsMonthDayTest.ts diff --git a/src/components/Search/SearchList/ListItem/DateCell.tsx b/src/components/Search/SearchList/ListItem/DateCell.tsx index 05da53973ba6..07b26d485b3d 100644 --- a/src/components/Search/SearchList/ListItem/DateCell.tsx +++ b/src/components/Search/SearchList/ListItem/DateCell.tsx @@ -43,13 +43,9 @@ function DateCell({date, showTooltip, isLargeScreenWidth, suffixText, shouldUseL if (shouldUseLocalTimeZone && date) { const localDate = getLocalDateFromDatetime(date); const isPastYear = localDate.getFullYear() !== getLocalDateFromDatetime().getFullYear(); - formattedDate = format(localDate, isPastYear ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT, {locale: dateFnsLocale}); + formattedDate = isPastYear ? format(localDate, CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT, {locale: dateFnsLocale}) : DateUtils.formatToMonthDay(localDate, dateFnsLocale); } else { - formattedDate = DateUtils.formatWithUTCTimeZone( - date, - DateUtils.doesDateBelongToAPastYear(date) ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT, - dateFnsLocale, - ); + formattedDate = DateUtils.formatToMonthDayWithOptionalYearInUTC(date, dateFnsLocale); } const displayText = suffixText ? `${formattedDate} • ${suffixText}` : formattedDate; diff --git a/src/components/Search/SearchList/ListItem/WithdrawalIDListItemHeader.tsx b/src/components/Search/SearchList/ListItem/WithdrawalIDListItemHeader.tsx index af940b373c1c..4248e4b03d9d 100644 --- a/src/components/Search/SearchList/ListItem/WithdrawalIDListItemHeader.tsx +++ b/src/components/Search/SearchList/ListItem/WithdrawalIDListItemHeader.tsx @@ -80,11 +80,7 @@ function WithdrawalIDListItemHeader({ const accountLabel = `${formattedBankName} ${maskedNumber}`; const {icon, iconSize, iconStyles} = getBankIcon({bankName: withdrawalIDItem.bankName, styles, maxIconSize: isLargeScreenWidth ? variables.w28 : undefined}); - const formattedWithdrawalDate = DateUtils.formatWithUTCTimeZone( - withdrawalIDItem.debitPosted, - DateUtils.doesDateBelongToAPastYear(withdrawalIDItem.debitPosted) ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT, - dateFnsLocale, - ); + const formattedWithdrawalDate = DateUtils.formatToMonthDayWithOptionalYearInUTC(withdrawalIDItem.debitPosted, dateFnsLocale); const {debitedAmount, debitedCurrency, creditedAmount, creditedCurrency} = withdrawalIDItem; const isCashBack = !!withdrawalIDItem.isCashBack; diff --git a/src/components/Search/SearchList/ListItem/getExpenseReportRowDisplayValues.ts b/src/components/Search/SearchList/ListItem/getExpenseReportRowDisplayValues.ts index 9549411a7a74..6e4b5ada6158 100644 --- a/src/components/Search/SearchList/ListItem/getExpenseReportRowDisplayValues.ts +++ b/src/components/Search/SearchList/ListItem/getExpenseReportRowDisplayValues.ts @@ -30,13 +30,7 @@ function getExpenseReportRowDisplayValues(item: ExpenseReportRowDisplayItem, {tr const expenseCount = (filteredTransactions?.length ? filteredTransactions.length : undefined) ?? item.transactionCount ?? 0; const expenseCountText = translate('iou.expenseCount', {count: expenseCount}); - const date = item.created - ? DateUtils.formatWithUTCTimeZone( - item.created, - DateUtils.doesDateBelongToAPastYear(item.created) ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT, - dateFnsLocale, - ) - : ''; + const date = item.created ? DateUtils.formatToMonthDayWithOptionalYearInUTC(item.created, dateFnsLocale) : ''; return {amount, expenseCountText, date}; } diff --git a/src/libs/DateUtils.ts b/src/libs/DateUtils.ts index 52ac53e4a927..a614f0acaa55 100644 --- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -208,7 +208,7 @@ function datetimeToCalendarTime(locale: Locale | undefined, datetime: string, cu return `${yesterdayAt} ${format(date, CONST.DATE.LOCAL_TIME_FORMAT, {locale: dateFnsLocale})}${tz}`; } if (date >= startOfCurrentWeek && date <= endOfCurrentWeek) { - return `${format(date, CONST.DATE.MONTH_DAY_ABBR_FORMAT, {locale: dateFnsLocale})} ${at} ${format(date, CONST.DATE.LOCAL_TIME_FORMAT, {locale: dateFnsLocale})}${tz}`; + return `${formatToMonthDay(date, dateFnsLocale)} ${at} ${format(date, CONST.DATE.LOCAL_TIME_FORMAT, {locale: dateFnsLocale})}${tz}`; } return `${format(date, CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT, {locale: dateFnsLocale})} ${at} ${format(date, CONST.DATE.LOCAL_TIME_FORMAT, {locale: dateFnsLocale})}${tz}`; } @@ -1027,6 +1027,41 @@ function doesDateBelongToAPastYear(date: string): boolean { return transactionYear !== new Date().getFullYear(); } +/** + * Building an `Intl.DateTimeFormat` costs far more than formatting with one, so instances are cached per language and + * timezone. + */ +const memoizedCreateMonthDayFormatter = memoize((localeCode: string, timeZone: string | undefined) => new Intl.DateTimeFormat(localeCode, {month: 'short', day: 'numeric', timeZone})); + +/** + * Formats a date as an abbreviated month and day, e.g. `Jun 20`. + * + * date-fns has no localized token for a month and day without a year, and a hand-written `MMM d` fixes the US order, + * so German put the month before the day and Japanese lost the suffix it writes after the day (`6月20日`). + * + * @param timeZone pass 'UTC' when the date is a calendar value that must not shift with the device's timezone + */ +function formatToMonthDay(date: Date, dateFnsLocale: DateFnsLocale | undefined, timeZone?: string): string { + if (!isValid(date)) { + return ''; + } + // date-fns falls back to en-US when given no locale, so this matches the date-fns formatters elsewhere in this file. + return memoizedCreateMonthDayFormatter(dateFnsLocale?.code ?? 'en-US', timeZone).format(date); +} + +/** + * Formats a calendar date (such as a transaction date) as an abbreviated month and day, adding the year only when the + * date is not in the current year. The date is read as UTC so the displayed day never shifts with the device's timezone. + * + * @returns Jun 20, or Jun 20, 2025 for a past year + */ +function formatToMonthDayWithOptionalYearInUTC(datetime: string, dateFnsLocale: DateFnsLocale | undefined): string { + if (doesDateBelongToAPastYear(datetime)) { + return formatWithUTCTimeZone(datetime, CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT, dateFnsLocale); + } + return formatToMonthDay(toDate(datetime, {timeZone: 'UTC'}), dateFnsLocale, 'UTC'); +} + /** * Returns a boolean value indicating whether the card has expired. * @param expiryMonth month when card expires (starts from 1 so can be any number between 1 and 12) @@ -1360,6 +1395,8 @@ const DateUtils = { getFormattedTransportDateAndHour, getFormattedCancellationDate, doesDateBelongToAPastYear, + formatToMonthDay, + formatToMonthDayWithOptionalYearInUTC, isCardExpired, getDifferenceInDaysFromNow, isValidDateString, diff --git a/src/libs/ReusableDistanceRoutesUtils.ts b/src/libs/ReusableDistanceRoutesUtils.ts index 4a1783c0a649..bab12ff25c9c 100644 --- a/src/libs/ReusableDistanceRoutesUtils.ts +++ b/src/libs/ReusableDistanceRoutesUtils.ts @@ -1,10 +1,12 @@ -import CONST from '@src/CONST'; import ONYXKEYS from '@src/ONYXKEYS'; import type {ReusableDistanceRoute, Transaction} from '@src/types/onyx'; import type {Waypoint, WaypointCollection} from '@src/types/onyx/Transaction'; +import type {Locale as DateFnsLocale} from 'date-fns'; import type {OnyxCollection} from 'react-native-onyx'; +import {toDate} from 'date-fns-tz'; + import DateUtils from './DateUtils'; import tokenizedSearch from './tokenizedSearch'; import {getWaypointIndex, hasPendingDistanceReceiptRegeneration} from './TransactionUtils'; @@ -56,8 +58,8 @@ function filterRoutes(routes: ReusableDistanceRoute[], searchValue: string): Reu /** * Formats the inserted timestamp of the source expense for the Last used badge */ -function formatLastUsed(inserted: string): string { - return DateUtils.formatWithUTCTimeZone(inserted, CONST.DATE.MONTH_DAY_ABBR_FORMAT, undefined); +function formatLastUsed(inserted: string, dateFnsLocale: DateFnsLocale | undefined): string { + return DateUtils.formatToMonthDay(toDate(inserted, {timeZone: 'UTC'}), dateFnsLocale, 'UTC'); } /** diff --git a/src/libs/TransactionPreviewUtils.ts b/src/libs/TransactionPreviewUtils.ts index 748e413cc96c..abd7969807f7 100644 --- a/src/libs/TransactionPreviewUtils.ts +++ b/src/libs/TransactionPreviewUtils.ts @@ -294,11 +294,7 @@ function getTransactionPreviewTextAndTranslationPaths({ let previewDateText: TranslationPathOrText | undefined; if (!isCreatedMissing(transaction)) { const created = getFormattedCreated(transaction); - const date = DateUtils.formatWithUTCTimeZone( - created, - DateUtils.doesDateBelongToAPastYear(created) ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT, - dateFnsLocale, - ); + const date = DateUtils.formatToMonthDayWithOptionalYearInUTC(created, dateFnsLocale); previewDateText = {text: date}; } diff --git a/src/pages/MultifactorAuthentication/AuthorizeTransactionPage/AuthorizeCardTransactionPreview.tsx b/src/pages/MultifactorAuthentication/AuthorizeTransactionPage/AuthorizeCardTransactionPreview.tsx index 658cb1a847ff..7cb8157f5c6b 100644 --- a/src/pages/MultifactorAuthentication/AuthorizeTransactionPage/AuthorizeCardTransactionPreview.tsx +++ b/src/pages/MultifactorAuthentication/AuthorizeTransactionPage/AuthorizeCardTransactionPreview.tsx @@ -56,9 +56,7 @@ function AuthorizeCardTransactionPreview({transactionID, amount, currency, merch ); } - const formattedDate = created - ? DateUtils.formatWithUTCTimeZone(created, DateUtils.doesDateBelongToAPastYear(created) ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT, dateFnsLocale) - : ''; + const formattedDate = created ? DateUtils.formatToMonthDayWithOptionalYearInUTC(created, dateFnsLocale) : ''; const headerText = [formattedDate, translate('common.card')].filter(Boolean).join(` ${CONST.DOT_SEPARATOR} `); let displayAmount = ''; if (amount !== undefined) { diff --git a/src/pages/home/RecentlyAddedSection/RecentlyAddedRow.tsx b/src/pages/home/RecentlyAddedSection/RecentlyAddedRow.tsx index 47435f202ea6..8accda57c232 100644 --- a/src/pages/home/RecentlyAddedSection/RecentlyAddedRow.tsx +++ b/src/pages/home/RecentlyAddedSection/RecentlyAddedRow.tsx @@ -42,11 +42,7 @@ function RecentlyAddedRow({expense, onPress, shouldShowSeparator, shouldShowRece const {convertToDisplayString} = useCurrencyListActions(); const {dateFnsLocale, translate} = useLocalize(); - const formattedDate = DateUtils.formatWithUTCTimeZone( - expense.created, - DateUtils.doesDateBelongToAPastYear(expense.created) ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT, - dateFnsLocale, - ); + const formattedDate = DateUtils.formatToMonthDayWithOptionalYearInUTC(expense.created, dateFnsLocale); const hasFailedScanAmountPlaceholder = isFailedScanAmountPlaceholder(expense.transaction, isSettled(expense.report)); const shouldShowScanFailureMessage = hasFailedScanAmountPlaceholder && expense.transaction.receipt?.state === CONST.IOU.RECEIPT_STATE.SCAN_FAILED; diff --git a/src/pages/iou/DynamicSplitExpensePage.tsx b/src/pages/iou/DynamicSplitExpensePage.tsx index df6d4ee28540..481b70f0cdfd 100644 --- a/src/pages/iou/DynamicSplitExpensePage.tsx +++ b/src/pages/iou/DynamicSplitExpensePage.tsx @@ -491,11 +491,7 @@ function DynamicSplitExpensePage({route}: DynamicSplitExpensePageProps) { const isSettled = isSettledReportUtils(currentItemReport?.reportID); const percentage = adjustedPercentages.at(index) ?? 0; - const date = DateUtils.formatWithUTCTimeZone( - item.created, - DateUtils.doesDateBelongToAPastYear(item.created) ? CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT : CONST.DATE.MONTH_DAY_ABBR_FORMAT, - dateFnsLocale, - ); + const date = DateUtils.formatToMonthDayWithOptionalYearInUTC(item.created, dateFnsLocale); previewHeaderText.unshift({text: date}, dotSeparator); if (isApproved) { diff --git a/src/pages/iou/request/step/ReuseRouteListItem.tsx b/src/pages/iou/request/step/ReuseRouteListItem.tsx index f4176a446bcf..c6391c058360 100644 --- a/src/pages/iou/request/step/ReuseRouteListItem.tsx +++ b/src/pages/iou/request/step/ReuseRouteListItem.tsx @@ -76,7 +76,7 @@ function ReuseRouteThumbnail({transactionID, receiptSource}: ReuseRouteThumbnail function ReuseRouteListItem({item, isFocused, isFocusVisible, showTooltip, isDisabled, onSelectRow, onDismissError, onFocus, shouldSyncFocus}: ListItemProps) { const styles = useThemeStyles(); const theme = useTheme(); - const {translate} = useLocalize(); + const {translate, dateFnsLocale} = useLocalize(); const icons = useMemoizedLazyExpensifyIcons(['Receipt', 'DotIndicatorUnfilled', 'Location']); if (!isReuseRouteListItemData(item)) { @@ -108,7 +108,7 @@ function ReuseRouteListItem({item, isFocused, isFocusVis diff --git a/tests/unit/DateUtilsMonthDayTest.ts b/tests/unit/DateUtilsMonthDayTest.ts new file mode 100644 index 000000000000..96c4de81d0e4 --- /dev/null +++ b/tests/unit/DateUtilsMonthDayTest.ts @@ -0,0 +1,68 @@ +// cspell:ignore Juni +import DateUtils from '@libs/DateUtils'; + +import {de} from 'date-fns/locale/de'; +import {es} from 'date-fns/locale/es'; +import {ja} from 'date-fns/locale/ja'; + +const CURRENT_YEAR = new Date().getFullYear(); + +describe('DateUtils month and day', () => { + describe('formatToMonthDay', () => { + it('keeps the English month and day unchanged', () => { + // Given a date and no locale, which falls back to en-US + // When it is formatted as a month and day + // Then English keeps the `MMM d` shape it had before + expect(DateUtils.formatToMonthDay(new Date(Date.UTC(2026, 5, 20)), undefined, 'UTC')).toBe('Jun 20'); + }); + + it('orders the month and day the way each language does', () => { + // Given languages that do not write a month and day in the US order + // When the same date is formatted in each + // Then German and Spanish put the day first and Japanese adds its day suffix. The hand-written `MMM d` + // produced `Juni 20` and `6月 20` instead. + const date = new Date(Date.UTC(2026, 5, 20)); + expect(DateUtils.formatToMonthDay(date, de, 'UTC')).toBe('20. Juni'); + expect(DateUtils.formatToMonthDay(date, es, 'UTC')).toBe('20 jun'); + expect(DateUtils.formatToMonthDay(date, ja, 'UTC')).toBe('6月20日'); + }); + + it('returns an empty string for an invalid date', () => { + // Given a date that cannot be read + // When it is formatted + // Then nothing is shown instead of `Intl` throwing a RangeError into the render + expect(DateUtils.formatToMonthDay(new Date('not a date'), undefined)).toBe(''); + }); + }); + + describe('formatToMonthDayWithOptionalYearInUTC', () => { + it('leaves out the year for a date in the current year', () => { + // Given a calendar date in the current year + // When it is formatted + // Then only the month and day are shown, in the language's own order + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-06-20`, undefined)).toBe('Jun 20'); + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-06-20`, de)).toBe('20. Juni'); + }); + + it('adds the year for a date in a past year', () => { + // Given a calendar date from a previous year + // When it is formatted + // Then the year is included so the date is not mistaken for this year's + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR - 2}-06-20`, undefined)).toBe(`Jun 20, ${CURRENT_YEAR - 2}`); + }); + + it('does not move the day for a midnight calendar date', () => { + // Given a calendar date stored as midnight, which would fall on the previous day in a timezone behind UTC + // When it is formatted + // Then the stored day is shown, because a transaction date is a calendar value rather than an instant + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-01-01 00:00:00`, undefined)).toBe('Jan 1'); + }); + + it('returns an empty string for an empty date', () => { + // Given a missing date + // When it is formatted + // Then nothing is shown + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC('', undefined)).toBe(''); + }); + }); +}); From 1365e4ddea6878630885be39a4fdbddc145620b5 Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Wed, 4 Nov 2026 14:57:31 +0530 Subject: [PATCH 2/4] Read calendar month-day dates' year in UTC formatToMonthDayWithOptionalYearInUTC shows the date in UTC, so read the date's year in UTC too before comparing it with the device's current year. Reading it in the device's timezone added a year to January 1 dates behind UTC. Add the DateCell, Last used and reused-route badge tests from #105846. --- src/libs/DateUtils.ts | 10 +- tests/ui/DateCellMonthDayTest.tsx | 115 ++++++++++++++++++ tests/ui/ReuseRouteLastUsedDateTest.tsx | 88 ++++++++++++++ tests/unit/DateUtilsMonthDayTest.ts | 15 +++ tests/unit/ReusableDistanceRoutesUtilsTest.ts | 19 ++- 5 files changed, 244 insertions(+), 3 deletions(-) create mode 100644 tests/ui/DateCellMonthDayTest.tsx create mode 100644 tests/ui/ReuseRouteLastUsedDateTest.tsx diff --git a/src/libs/DateUtils.ts b/src/libs/DateUtils.ts index a614f0acaa55..bbf766e5bea3 100644 --- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -1056,10 +1056,16 @@ function formatToMonthDay(date: Date, dateFnsLocale: DateFnsLocale | undefined, * @returns Jun 20, or Jun 20, 2025 for a past year */ function formatToMonthDayWithOptionalYearInUTC(datetime: string, dateFnsLocale: DateFnsLocale | undefined): string { - if (doesDateBelongToAPastYear(datetime)) { + const date = toDate(datetime, {timeZone: 'UTC'}); + if (!isValid(date)) { + return ''; + } + // Read the date's year in UTC, the timezone it is shown in, and compare it with the device's current year. Reading the + // date in the device's timezone treated a January 1 date as the previous year behind UTC and added a year to it. + if (date.getUTCFullYear() !== new Date().getFullYear()) { return formatWithUTCTimeZone(datetime, CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT, dateFnsLocale); } - return formatToMonthDay(toDate(datetime, {timeZone: 'UTC'}), dateFnsLocale, 'UTC'); + return formatToMonthDay(date, dateFnsLocale, 'UTC'); } /** diff --git a/tests/ui/DateCellMonthDayTest.tsx b/tests/ui/DateCellMonthDayTest.tsx new file mode 100644 index 000000000000..68966ef0c7ca --- /dev/null +++ b/tests/ui/DateCellMonthDayTest.tsx @@ -0,0 +1,115 @@ +import {act, render, screen} from '@testing-library/react-native'; + +import ComposeProviders from '@components/ComposeProviders'; +import {CurrentUserPersonalDetailsProvider} from '@components/CurrentUserPersonalDetailsProvider'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import DateCell from '@components/Search/SearchList/ListItem/DateCell'; + +import useResponsiveLayout from '@hooks/useResponsiveLayout'; + +import CONST from '@src/CONST'; +import type {Locale} from '@src/CONST/LOCALES'; +import ONYXKEYS from '@src/ONYXKEYS'; + +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +jest.mock('@libs/Navigation/Navigation'); + +jest.mock('@hooks/useResponsiveLayout', () => jest.fn()); +const mockedUseResponsiveLayout = jest.mocked(useResponsiveLayout); + +function renderDateCell(date: string, shouldUseLocalTimeZone = false) { + return render( + + + , + ); +} + +async function setPreferredLocale(locale: Locale) { + await act(async () => { + await Onyx.set(ONYXKEYS.NVP_PREFERRED_LOCALE, locale); + }); + await waitForBatchedUpdatesWithAct(); +} + +describe('DateCell month and day', () => { + beforeAll(() => + Onyx.init({ + keys: ONYXKEYS, + evictableKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS], + }), + ); + + beforeEach(() => { + jest.useFakeTimers({doNotFake: ['setImmediate', 'nextTick']}); + jest.setSystemTime(new Date('2026-11-03T20:00:00Z')); + mockedUseResponsiveLayout.mockReturnValue({ + isLargeScreenWidth: true, + shouldUseNarrowLayout: false, + isSmallScreenWidth: false, + isMediumScreenWidth: false, + isExtraSmallScreenWidth: false, + isExtraSmallScreenHeight: false, + isExtraLargeScreenWidth: true, + isSmallScreen: false, + isInNarrowPaneModal: false, + onboardingIsMediumOrLargerScreenWidth: true, + isInLandscapeMode: false, + }); + }); + + afterEach(async () => { + await act(async () => { + await Onyx.clear(); + }); + jest.clearAllMocks(); + jest.useRealTimers(); + }); + + it.each([ + [CONST.LOCALES.EN, 'Jan 22'], + [CONST.LOCALES.DE, '22. Jan.'], + [CONST.LOCALES.ES, '22 ene'], + [CONST.LOCALES.JA, '1月22日'], + ] as const)('uses %s month and day conventions for a date in the current year', async (locale, expected) => { + // Given an expense dated this year and an explicit app language + await setPreferredLocale(locale); + + // When its date cell renders through the real locale provider + renderDateCell('2026-01-22'); + await waitForBatchedUpdatesWithAct(); + + // Then the month and day follow that language's order and the year is left out + expect(screen.getByText(expected)).toBeOnTheScreen(); + }); + + it('compares the year in the selected timezone for an instant near midnight', async () => { + // Given an instant on January 1 UTC that is still December 31 for a viewer in Los Angeles + jest.setSystemTime(new Date('2026-06-01T12:00:00Z')); + const accountID = 999; + await act(async () => { + await Onyx.set(ONYXKEYS.SESSION, {accountID}); + await Onyx.set(ONYXKEYS.PERSONAL_DETAILS_LIST, { + [accountID]: {accountID, timezone: {automatic: false, selected: 'America/Los_Angeles'}}, + }); + }); + await setPreferredLocale(CONST.LOCALES.EN); + + // When the timestamp column displays that instant in the selected timezone + renderDateCell('2026-01-01 01:00:00', true); + await waitForBatchedUpdatesWithAct(); + + // Then both the visible day and the decision to include a year use December 31, 2025 + expect(screen.getByText('Dec 31, 2025')).toBeOnTheScreen(); + }); +}); diff --git a/tests/ui/ReuseRouteLastUsedDateTest.tsx b/tests/ui/ReuseRouteLastUsedDateTest.tsx new file mode 100644 index 000000000000..1587341f834b --- /dev/null +++ b/tests/ui/ReuseRouteLastUsedDateTest.tsx @@ -0,0 +1,88 @@ +// cspell:ignore Zuletzt verwendet +import {act, render, screen} from '@testing-library/react-native'; + +import ComposeProviders from '@components/ComposeProviders'; +import {CurrentUserPersonalDetailsContext} from '@components/CurrentUserPersonalDetailsProvider'; +import {LocaleContextProvider} from '@components/LocaleContextProvider'; +import OnyxListItemProvider from '@components/OnyxListItemProvider'; +import type {ListItem, ListItemProps} from '@components/SelectionList/ListItem/types'; + +import ReuseRouteListItem from '@pages/iou/request/step/ReuseRouteListItem'; + +import CONST from '@src/CONST'; +import ONYXKEYS from '@src/ONYXKEYS'; +import type {ReusableDistanceRoute} from '@src/types/onyx'; + +import type {NavigationProp, ParamListBase} from '@react-navigation/native'; + +import {NavigationContext} from '@react-navigation/native'; +import React from 'react'; +import Onyx from 'react-native-onyx'; + +import createMock from '../utils/createMock'; +import {setupGlobalFetchMock} from '../utils/TestHelper'; +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +setupGlobalFetchMock(); + +jest.mock('@libs/Navigation/Navigation'); +jest.mock('@components/EReceiptThumbnail', () => () => null); + +function renderSurface(children: React.ReactNode) { + const navigation = createMock>({isFocused: () => true, addListener: () => () => {}}); + return render( + + + {children} + + , + ); +} + +describe('Reused route Last used date', () => { + beforeAll(() => Onyx.init({keys: ONYXKEYS, evictableKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS]})); + + beforeEach(async () => { + jest.useFakeTimers({doNotFake: ['setImmediate', 'nextTick']}); + jest.setSystemTime(new Date('2026-11-03T20:00:00Z')); + await act(async () => { + await Onyx.multiSet({ + [ONYXKEYS.SESSION]: {accountID: 999, email: 'date-test@example.com'}, + [ONYXKEYS.NVP_PREFERRED_LOCALE]: CONST.LOCALES.DE, + [ONYXKEYS.HAS_LOADED_APP]: true, + }); + }); + }); + + afterEach(async () => { + await act(async () => Onyx.clear()); + jest.useRealTimers(); + jest.clearAllMocks(); + }); + + it('updates a reused-route badge when the app language changes while the row stays mounted', async () => { + // Given a reusable distance route whose source expense has a fixed UTC insertion date + const props = createMock>({ + item: { + keyForList: 'route', + route: { + transactionID: '100', + inserted: '2026-01-22 12:00:00', + distance: 3.5, + waypoints: {waypoint0: {address: 'Start'}, waypoint1: {address: 'End'}}, + }, + }, + onSelectRow: jest.fn(), + }); + renderSurface(); + await waitForBatchedUpdatesWithAct(); + expect(screen.getByText('Zuletzt verwendet am 22. Jan.')).toBeOnTheScreen(); + + // When the app language changes without replacing the row or its route + await act(async () => Onyx.set(ONYXKEYS.NVP_PREFERRED_LOCALE, CONST.LOCALES.JA)); + await waitForBatchedUpdatesWithAct(); + + // Then both the badge copy and the date follow the reactive locale + expect(screen.getByText('最終利用日:1月22日')).toBeOnTheScreen(); + }); +}); diff --git a/tests/unit/DateUtilsMonthDayTest.ts b/tests/unit/DateUtilsMonthDayTest.ts index 96c4de81d0e4..c8ca012e7ecd 100644 --- a/tests/unit/DateUtilsMonthDayTest.ts +++ b/tests/unit/DateUtilsMonthDayTest.ts @@ -58,6 +58,21 @@ describe('DateUtils month and day', () => { expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-01-01 00:00:00`, undefined)).toBe('Jan 1'); }); + it('leaves out the year for January 1 of the current year in every timezone', () => { + // Given a stored January 1 date, at midday on January 1 in UTC, when it is January 1 on every device + jest.useFakeTimers(); + jest.setSystemTime(new Date('2026-01-01T12:00:00Z')); + + try { + // When it is formatted + // Then the date's year is read in UTC, the timezone it is shown in. Read in the device's timezone, the + // stored midnight falls on December 31 behind UTC and the date was mistaken for the previous year. + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC('2026-01-01', de)).toBe('1. Jan.'); + } finally { + jest.useRealTimers(); + } + }); + it('returns an empty string for an empty date', () => { // Given a missing date // When it is formatted diff --git a/tests/unit/ReusableDistanceRoutesUtilsTest.ts b/tests/unit/ReusableDistanceRoutesUtilsTest.ts index d20df43e4dc9..a6309084a13a 100644 --- a/tests/unit/ReusableDistanceRoutesUtilsTest.ts +++ b/tests/unit/ReusableDistanceRoutesUtilsTest.ts @@ -1,8 +1,11 @@ +import {de} from 'date-fns/locale/de'; +import {ja} from 'date-fns/locale/ja'; + import type {ReusableDistanceRoute, Transaction} from '../../src/types/onyx'; import type {WaypointCollection} from '../../src/types/onyx/Transaction'; import CONST from '../../src/CONST'; -import {filterRoutes, getAvailableReusableDistanceRoutes, getOrderedWaypoints, getRouteEndpoints, getRouteThumbnailSource} from '../../src/libs/ReusableDistanceRoutesUtils'; +import {filterRoutes, formatLastUsed, getAvailableReusableDistanceRoutes, getOrderedWaypoints, getRouteEndpoints, getRouteThumbnailSource} from '../../src/libs/ReusableDistanceRoutesUtils'; import ONYXKEYS from '../../src/ONYXKEYS'; const createRoute = (transactionID: string, addresses: string[]): ReusableDistanceRoute => ({ @@ -16,6 +19,20 @@ const createRoute = (transactionID: string, addresses: string[]): ReusableDistan }); describe('ReusableDistanceRoutesUtils', () => { + it.each([ + ['German', de, '22. Jan.'], + ['Japanese', ja, '1月22日'], + ] as const)('formats the Last used date in %s', (languageName, locale, expected) => { + // Given a source expense inserted late on a UTC calendar day + const inserted = '2026-01-22 23:30:00'; + + // When the badge asks for an explicit-locale date + const label = formatLastUsed(inserted, locale); + + // Then the label uses that locale without moving to a different day + expect(label).toBe(expected); + }); + describe('filterRoutes', () => { const routes = [ createRoute('1', ['Expensify Lounge, San Francisco, CA', 'Marina Green East Beach, San Francisco, CA']), From e5eee35aef1efb06d62628a4c44d1d7dfc6e09f8 Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Wed, 4 Nov 2026 22:08:20 +0530 Subject: [PATCH 3/4] Follow device timezone changes in the cached month-day formatter A cached Intl.DateTimeFormat keeps the device timezone from when it was created. Format local dates in UTC and copy their current local fields instead. Dates formatted in an explicit timezone are unchanged. --- src/libs/DateUtils.ts | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/libs/DateUtils.ts b/src/libs/DateUtils.ts index bbf766e5bea3..c7e9dcd2a397 100644 --- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -68,6 +68,21 @@ function isDate(arg: unknown): arg is Date { return Object.prototype.toString.call(arg) === '[object Date]'; } +/** + * Copies a date's wall-clock fields in the device's timezone onto the same fields in UTC. + * + * An `Intl.DateTimeFormat` created without a `timeZone` keeps the device's timezone from when it was created, so a + * cached one would keep showing the old day after the device moves to another timezone. Cached formatters are created + * with `timeZone: 'UTC'` instead and given the result of this function, which reads the device's timezone on every call. + */ +function toUTCWallClockDate(date: Date): Date { + const utcDate = new Date(0); + // `setUTCFullYear` rather than `Date.UTC`, which treats the years 0 to 99 as 1900 to 1999 + utcDate.setUTCFullYear(date.getFullYear(), date.getMonth(), date.getDate()); + utcDate.setUTCHours(date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()); + return utcDate; +} + /** * Get the day of the week that the week starts on */ @@ -1029,9 +1044,10 @@ function doesDateBelongToAPastYear(date: string): boolean { /** * Building an `Intl.DateTimeFormat` costs far more than formatting with one, so instances are cached per language and - * timezone. + * timezone. A formatter with no timezone would keep the device's timezone from when it was created, so local dates are + * formatted in UTC after `toUTCWallClockDate` instead. */ -const memoizedCreateMonthDayFormatter = memoize((localeCode: string, timeZone: string | undefined) => new Intl.DateTimeFormat(localeCode, {month: 'short', day: 'numeric', timeZone})); +const memoizedCreateMonthDayFormatter = memoize((localeCode: string, timeZone: string) => new Intl.DateTimeFormat(localeCode, {month: 'short', day: 'numeric', timeZone})); /** * Formats a date as an abbreviated month and day, e.g. `Jun 20`. @@ -1046,7 +1062,11 @@ function formatToMonthDay(date: Date, dateFnsLocale: DateFnsLocale | undefined, return ''; } // date-fns falls back to en-US when given no locale, so this matches the date-fns formatters elsewhere in this file. - return memoizedCreateMonthDayFormatter(dateFnsLocale?.code ?? 'en-US', timeZone).format(date); + const localeCode = dateFnsLocale?.code ?? 'en-US'; + if (timeZone) { + return memoizedCreateMonthDayFormatter(localeCode, timeZone).format(date); + } + return memoizedCreateMonthDayFormatter(localeCode, 'UTC').format(toUTCWallClockDate(date)); } /** From 6aea14347ac62e1fa67f0041f6e0a3e3e606e012 Mon Sep 17 00:00:00 2001 From: Shubham Agrawal Date: Thu, 5 Nov 2026 14:57:36 +0530 Subject: [PATCH 4/4] Move the month-day tests into DateUtilsTest --- tests/unit/DateUtilsMonthDayTest.ts | 83 ----------------------------- tests/unit/DateUtilsTest.ts | 79 +++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 83 deletions(-) delete mode 100644 tests/unit/DateUtilsMonthDayTest.ts diff --git a/tests/unit/DateUtilsMonthDayTest.ts b/tests/unit/DateUtilsMonthDayTest.ts deleted file mode 100644 index c8ca012e7ecd..000000000000 --- a/tests/unit/DateUtilsMonthDayTest.ts +++ /dev/null @@ -1,83 +0,0 @@ -// cspell:ignore Juni -import DateUtils from '@libs/DateUtils'; - -import {de} from 'date-fns/locale/de'; -import {es} from 'date-fns/locale/es'; -import {ja} from 'date-fns/locale/ja'; - -const CURRENT_YEAR = new Date().getFullYear(); - -describe('DateUtils month and day', () => { - describe('formatToMonthDay', () => { - it('keeps the English month and day unchanged', () => { - // Given a date and no locale, which falls back to en-US - // When it is formatted as a month and day - // Then English keeps the `MMM d` shape it had before - expect(DateUtils.formatToMonthDay(new Date(Date.UTC(2026, 5, 20)), undefined, 'UTC')).toBe('Jun 20'); - }); - - it('orders the month and day the way each language does', () => { - // Given languages that do not write a month and day in the US order - // When the same date is formatted in each - // Then German and Spanish put the day first and Japanese adds its day suffix. The hand-written `MMM d` - // produced `Juni 20` and `6月 20` instead. - const date = new Date(Date.UTC(2026, 5, 20)); - expect(DateUtils.formatToMonthDay(date, de, 'UTC')).toBe('20. Juni'); - expect(DateUtils.formatToMonthDay(date, es, 'UTC')).toBe('20 jun'); - expect(DateUtils.formatToMonthDay(date, ja, 'UTC')).toBe('6月20日'); - }); - - it('returns an empty string for an invalid date', () => { - // Given a date that cannot be read - // When it is formatted - // Then nothing is shown instead of `Intl` throwing a RangeError into the render - expect(DateUtils.formatToMonthDay(new Date('not a date'), undefined)).toBe(''); - }); - }); - - describe('formatToMonthDayWithOptionalYearInUTC', () => { - it('leaves out the year for a date in the current year', () => { - // Given a calendar date in the current year - // When it is formatted - // Then only the month and day are shown, in the language's own order - expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-06-20`, undefined)).toBe('Jun 20'); - expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-06-20`, de)).toBe('20. Juni'); - }); - - it('adds the year for a date in a past year', () => { - // Given a calendar date from a previous year - // When it is formatted - // Then the year is included so the date is not mistaken for this year's - expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR - 2}-06-20`, undefined)).toBe(`Jun 20, ${CURRENT_YEAR - 2}`); - }); - - it('does not move the day for a midnight calendar date', () => { - // Given a calendar date stored as midnight, which would fall on the previous day in a timezone behind UTC - // When it is formatted - // Then the stored day is shown, because a transaction date is a calendar value rather than an instant - expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-01-01 00:00:00`, undefined)).toBe('Jan 1'); - }); - - it('leaves out the year for January 1 of the current year in every timezone', () => { - // Given a stored January 1 date, at midday on January 1 in UTC, when it is January 1 on every device - jest.useFakeTimers(); - jest.setSystemTime(new Date('2026-01-01T12:00:00Z')); - - try { - // When it is formatted - // Then the date's year is read in UTC, the timezone it is shown in. Read in the device's timezone, the - // stored midnight falls on December 31 behind UTC and the date was mistaken for the previous year. - expect(DateUtils.formatToMonthDayWithOptionalYearInUTC('2026-01-01', de)).toBe('1. Jan.'); - } finally { - jest.useRealTimers(); - } - }); - - it('returns an empty string for an empty date', () => { - // Given a missing date - // When it is formatted - // Then nothing is shown - expect(DateUtils.formatToMonthDayWithOptionalYearInUTC('', undefined)).toBe(''); - }); - }); -}); diff --git a/tests/unit/DateUtilsTest.ts b/tests/unit/DateUtilsTest.ts index fa91c6e41574..7d8605b14254 100644 --- a/tests/unit/DateUtilsTest.ts +++ b/tests/unit/DateUtilsTest.ts @@ -17,6 +17,7 @@ import {addDays, addMinutes, endOfDay, format, set, setHours, setMinutes, startO import {fromZonedTime, toZonedTime, format as tzFormat} from 'date-fns-tz'; import {de} from 'date-fns/locale/de'; import {el} from 'date-fns/locale/el'; +import {es} from 'date-fns/locale/es'; import {fr} from 'date-fns/locale/fr'; import {ja} from 'date-fns/locale/ja'; import {nl} from 'date-fns/locale/nl'; @@ -1132,4 +1133,82 @@ describe('DateUtils', () => { expect(DateUtils.getShortFormattedDateRangeForSearch('2026-09-28', '2026-10-04', undefined, false)).toBe('Sep 28 - Oct 4'); }); }); + + describe('month and day', () => { + // cspell:ignore Juni + const CURRENT_YEAR = new Date().getFullYear(); + + describe('formatToMonthDay', () => { + it('keeps the English month and day unchanged', () => { + // Given a date and no locale, which falls back to en-US + // When it is formatted as a month and day + // Then English keeps the `MMM d` shape it had before + expect(DateUtils.formatToMonthDay(new Date(Date.UTC(2026, 5, 20)), undefined, 'UTC')).toBe('Jun 20'); + }); + + it('orders the month and day the way each language does', () => { + // Given languages that do not write a month and day in the US order + // When the same date is formatted in each + // Then German and Spanish put the day first and Japanese adds its day suffix. The hand-written `MMM d` + // produced `Juni 20` and `6月 20` instead. + const date = new Date(Date.UTC(2026, 5, 20)); + expect(DateUtils.formatToMonthDay(date, de, 'UTC')).toBe('20. Juni'); + expect(DateUtils.formatToMonthDay(date, es, 'UTC')).toBe('20 jun'); + expect(DateUtils.formatToMonthDay(date, ja, 'UTC')).toBe('6月20日'); + }); + + it('returns an empty string for an invalid date', () => { + // Given a date that cannot be read + // When it is formatted + // Then nothing is shown instead of `Intl` throwing a RangeError into the render + expect(DateUtils.formatToMonthDay(new Date('not a date'), undefined)).toBe(''); + }); + }); + + describe('formatToMonthDayWithOptionalYearInUTC', () => { + it('leaves out the year for a date in the current year', () => { + // Given a calendar date in the current year + // When it is formatted + // Then only the month and day are shown, in the language's own order + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-06-20`, undefined)).toBe('Jun 20'); + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-06-20`, de)).toBe('20. Juni'); + }); + + it('adds the year for a date in a past year', () => { + // Given a calendar date from a previous year + // When it is formatted + // Then the year is included so the date is not mistaken for this year's + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR - 2}-06-20`, undefined)).toBe(`Jun 20, ${CURRENT_YEAR - 2}`); + }); + + it('does not move the day for a midnight calendar date', () => { + // Given a calendar date stored as midnight, which would fall on the previous day in a timezone behind UTC + // When it is formatted + // Then the stored day is shown, because a transaction date is a calendar value rather than an instant + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC(`${CURRENT_YEAR}-01-01 00:00:00`, undefined)).toBe('Jan 1'); + }); + + it('leaves out the year for January 1 of the current year in every timezone', () => { + // Given a stored January 1 date, at midday on January 1 in UTC, when it is January 1 on every device + jest.useFakeTimers(); + jest.setSystemTime(new Date('2026-01-01T12:00:00Z')); + + try { + // When it is formatted + // Then the date's year is read in UTC, the timezone it is shown in. Read in the device's timezone, the + // stored midnight falls on December 31 behind UTC and the date was mistaken for the previous year. + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC('2026-01-01', de)).toBe('1. Jan.'); + } finally { + jest.useRealTimers(); + } + }); + + it('returns an empty string for an empty date', () => { + // Given a missing date + // When it is formatted + // Then nothing is shown + expect(DateUtils.formatToMonthDayWithOptionalYearInUTC('', undefined)).toBe(''); + }); + }); + }); });