diff --git a/src/libs/DateUtils.ts b/src/libs/DateUtils.ts index 16978787806e..17739d63c9c7 100644 --- a/src/libs/DateUtils.ts +++ b/src/libs/DateUtils.ts @@ -33,6 +33,7 @@ import ONYXKEYS from '@src/ONYXKEYS'; import {SelectedTimezone, Timezone} from '@src/types/onyx/PersonalDetails'; import * as CurrentDate from './actions/CurrentDate'; import * as Localize from './Localize'; +import Log from './Log'; type CustomStatusTypes = (typeof CONST.CUSTOM_STATUS_TYPES)[keyof typeof CONST.CUSTOM_STATUS_TYPES]; type TimePeriod = 'AM' | 'PM'; @@ -91,7 +92,16 @@ function setLocale(localeString: Locale) { function getLocalDateFromDatetime(locale: Locale, datetime?: string, currentSelectedTimezone: SelectedTimezone = timezone.selected): Date { setLocale(locale); if (!datetime) { - return utcToZonedTime(new Date(), currentSelectedTimezone); + const res = utcToZonedTime(new Date(), currentSelectedTimezone); + if (Number.isNaN(res.getTime())) { + Log.warn('DateUtils.getLocalDateFromDatetime: utcToZonedTime returned an invalid date. Returning current date.', { + locale, + datetime, + currentSelectedTimezone, + }); + return new Date(); + } + return res; } const parsedDatetime = new Date(`${datetime}Z`); return utcToZonedTime(parsedDatetime, currentSelectedTimezone); diff --git a/tests/unit/DateUtilsTest.js b/tests/unit/DateUtilsTest.js index 0303085f1172..7480da456d7f 100644 --- a/tests/unit/DateUtilsTest.js +++ b/tests/unit/DateUtilsTest.js @@ -52,6 +52,11 @@ describe('DateUtils', () => { expect(tzFormat(localDate, CONST.DATE.FNS_TIMEZONE_FORMAT_STRING, {timeZone: timezone})).toEqual('2022-11-06T16:00:00-08:00'); }); + it('should fallback to current date when getLocalDateFromDatetime is failing', () => { + const localDate = DateUtils.getLocalDateFromDatetime(LOCALE, undefined, 'InvalidTimezone'); + expect(localDate.getTime()).not.toBeNaN(); + }); + it('should return the date in calendar time when calling datetimeToCalendarTime', () => { const today = setMinutes(setHours(new Date(), 14), 32); expect(DateUtils.datetimeToCalendarTime(LOCALE, today)).toBe('Today at 2:32 PM');