Skip to content

Commit

Permalink
Merge pull request #33223 from margelo/fix/dateutils-crash
Browse files Browse the repository at this point in the history
fix: detect if date is NaN in getLocalDateFromDatetime
  • Loading branch information
mountiny authored Dec 26, 2023
2 parents bcee124 + 81ea1f6 commit de5a943
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/libs/DateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions tests/unit/DateUtilsTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit de5a943

Please sign in to comment.