From 81ea1f6961ac55cfe4f6b3473e693ea94187e3a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Mon, 18 Dec 2023 13:20:10 +0100 Subject: [PATCH] detect if date is NaN --- src/libs/DateUtils.ts | 12 +++++++++++- tests/unit/DateUtilsTest.js | 5 +++++ 2 files changed, 16 insertions(+), 1 deletion(-) 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');