diff --git a/core/src/components/datetime/test/format.spec.ts b/core/src/components/datetime/test/format.spec.ts index 74e81bf890..73ef7245dc 100644 --- a/core/src/components/datetime/test/format.spec.ts +++ b/core/src/components/datetime/test/format.spec.ts @@ -168,4 +168,13 @@ describe('getLocalizedTime', () => { expect(getLocalizedTime('en-GB', datetimeParts, false)).toEqual('12:00 am'); }); + it('should parse time-only values correctly', () => { + const datetimeParts = { + hour: 22, + minute: 40, + }; + + expect(getLocalizedTime('en-US', datetimeParts, false)).toEqual('10:40 PM'); + expect(getLocalizedTime('en-US', datetimeParts, true)).toEqual('22:40'); + }); }); diff --git a/core/src/components/datetime/utils/format.ts b/core/src/components/datetime/utils/format.ts index 53901f4a58..b335efb4c8 100644 --- a/core/src/components/datetime/utils/format.ts +++ b/core/src/components/datetime/utils/format.ts @@ -11,7 +11,12 @@ const getFormattedDayPeriod = (dayPeriod?: string) => { }; export const getLocalizedTime = (locale: string, refParts: DatetimeParts, use24Hour: boolean): string => { - if (refParts.hour === undefined || refParts.minute === undefined) { + const timeParts: Pick = { + hour: refParts.hour, + minute: refParts.minute, + }; + + if (timeParts.hour === undefined || timeParts.minute === undefined) { return 'Invalid Time'; } @@ -27,7 +32,21 @@ export const getLocalizedTime = (locale: string, refParts: DatetimeParts, use24H }).format( new Date( convertDataToISO({ - ...refParts, + /** + * JS uses a simplified ISO 8601 format which allows for + * date-only formats and date-time formats, but not + * time-only formats: https://tc39.es/ecma262/#sec-date-time-string-format + * As a result, developers who only pass a time will get + * an "Invalid Date" error. To account for this, we make sure that + * year/day/month values are set when passing to new Date(). + * The Intl.DateTimeFormat call above only uses the hour/minute + * values, so passing these date values should have no impact + * on the time output. + */ + year: 2023, + day: 1, + month: 1, + ...timeParts, // TODO: FW-1831 will remove the need to manually set the tzOffset to undefined tzOffset: undefined, })