Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 2 additions & 6 deletions src/components/Search/SearchList/ListItem/DateCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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};
}
Expand Down
50 changes: 49 additions & 1 deletion src/libs/DateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -1541,6 +1587,8 @@ const DateUtils = {
getFormattedTransportDateAndHour,
getFormattedCancellationDate,
doesDateBelongToAPastYear,
formatToMonthDay,
formatToMonthDayWithOptionalYearInUTC,
isCardExpired,
getDifferenceInDaysFromNow,
isValidDateString,
Expand Down
8 changes: 5 additions & 3 deletions src/libs/ReusableDistanceRoutesUtils.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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');
}

/**
Expand Down
6 changes: 1 addition & 5 deletions src/libs/TransactionPreviewUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
6 changes: 1 addition & 5 deletions src/pages/home/RecentlyAddedSection/RecentlyAddedRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 1 addition & 5 deletions src/pages/iou/DynamicSplitExpensePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
4 changes: 2 additions & 2 deletions src/pages/iou/request/step/ReuseRouteListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ function ReuseRouteThumbnail({transactionID, receiptSource}: ReuseRouteThumbnail
function ReuseRouteListItem<TItem extends ListItem>({item, isFocused, isFocusVisible, showTooltip, isDisabled, onSelectRow, onDismissError, onFocus, shouldSyncFocus}: ListItemProps<TItem>) {
const styles = useThemeStyles();
const theme = useTheme();
const {translate} = useLocalize();
const {translate, dateFnsLocale} = useLocalize();
const icons = useMemoizedLazyExpensifyIcons(['Receipt', 'DotIndicatorUnfilled', 'Location']);

if (!isReuseRouteListItemData(item)) {
Expand Down Expand Up @@ -108,7 +108,7 @@ function ReuseRouteListItem<TItem extends ListItem>({item, isFocused, isFocusVis
</View>
</View>
<Badge
text={translate('distance.lastUsed', {date: formatLastUsed(item.route.inserted)})}
text={translate('distance.lastUsed', {date: formatLastUsed(item.route.inserted, dateFnsLocale)})}
badgeStyles={styles.reuseRouteLastUsedBadge}
textStyles={styles.reuseRouteLastUsedBadgeText}
/>
Expand Down
115 changes: 115 additions & 0 deletions tests/ui/DateCellMonthDayTest.tsx
Original file line number Diff line number Diff line change
@@ -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(
<ComposeProviders components={[OnyxListItemProvider, CurrentUserPersonalDetailsProvider, LocaleContextProvider]}>
<DateCell
date={date}
shouldUseLocalTimeZone={shouldUseLocalTimeZone}
showTooltip={false}
isLargeScreenWidth
/>
</ComposeProviders>,
);
}

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();
});
});
Loading
Loading