fix(datetime-button): time-only values are parsed (#26852)

resolves #26851
This commit is contained in:
Liam DeBeasi
2023-03-02 09:09:01 -05:00
committed by GitHub
parent b46c78ec88
commit f54fc18884
2 changed files with 30 additions and 2 deletions

View File

@ -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');
});
});

View File

@ -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<DatetimeParts, 'hour' | 'minute'> = {
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,
})