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 a0e8c6261d54..d83f409b452d 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 12fae3949c2f..aaec4c63b8d2 100644 --- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -223,7 +223,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}`; } @@ -1114,6 +1114,52 @@ 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. 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) => 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. + const localeCode = dateFnsLocale?.code ?? 'en-US'; + if (timeZone) { + return memoizedCreateMonthDayFormatter(localeCode, timeZone).format(date); + } + return memoizedCreateMonthDayFormatter(localeCode, 'UTC').format(toUTCWallClockDate(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 { + 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(date, 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) @@ -1541,6 +1587,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 147892e526bc..779098cb5586 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 d3cac52b211d..34bc4a815a49 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/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/DateUtilsTest.ts b/tests/unit/DateUtilsTest.ts index c43f42f9e13a..184787a097c7 100644 --- a/tests/unit/DateUtilsTest.ts +++ b/tests/unit/DateUtilsTest.ts @@ -1282,6 +1282,84 @@ describe('DateUtils', () => { }); }); + 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(''); + }); + }); + }); + describe('local long date', () => { // cspell:ignore Juni junio describe('formatToLongDate', () => { 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']),