Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: detect if date is NaN in getLocalDateFromDatetime #33223

Merged
merged 1 commit into from
Dec 26, 2023
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
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
Loading