(
locale: string,
refParts: DatetimeParts,
hourCycle: DatetimeHourCycle,
formatOptions: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: 'numeric' }
)
| 33 | }; |
| 34 | |
| 35 | export const getLocalizedTime = ( |
| 36 | locale: string, |
| 37 | refParts: DatetimeParts, |
| 38 | hourCycle: DatetimeHourCycle, |
| 39 | formatOptions: Intl.DateTimeFormatOptions = { hour: 'numeric', minute: 'numeric' } |
| 40 | ): string => { |
| 41 | const timeParts: Pick<DatetimeParts, 'hour' | 'minute'> = { |
| 42 | hour: refParts.hour, |
| 43 | minute: refParts.minute, |
| 44 | }; |
| 45 | |
| 46 | if (timeParts.hour === undefined || timeParts.minute === undefined) { |
| 47 | return 'Invalid Time'; |
| 48 | } |
| 49 | |
| 50 | return new Intl.DateTimeFormat(locale, { |
| 51 | ...stripTimeZone(formatOptions), |
| 52 | /** |
| 53 | * We use hourCycle here instead of hour12 due to: |
| 54 | * https://bugs.chromium.org/p/chromium/issues/detail?id=1347316&q=hour12&can=2 |
| 55 | */ |
| 56 | hourCycle, |
| 57 | /** |
| 58 | * Setting Z at the end indicates that this |
| 59 | * date string is in the UTC time zone. This |
| 60 | * prevents new Date from adding the time zone |
| 61 | * offset when getting the ISO string. |
| 62 | */ |
| 63 | }).format( |
| 64 | new Date( |
| 65 | convertDataToISO({ |
| 66 | /** |
| 67 | * JS uses a simplified ISO 8601 format which allows for |
| 68 | * date-only formats and date-time formats, but not |
| 69 | * time-only formats: https://tc39.es/ecma262/#sec-date-time-string-format |
| 70 | * As a result, developers who only pass a time will get |
| 71 | * an "Invalid Date" error. To account for this, we make sure that |
| 72 | * year/day/month values are set when passing to new Date(). |
| 73 | * The Intl.DateTimeFormat call above only uses the hour/minute |
| 74 | * values, so passing these date values should have no impact |
| 75 | * on the time output. |
| 76 | */ |
| 77 | year: 2023, |
| 78 | day: 1, |
| 79 | month: 1, |
| 80 | ...timeParts, |
| 81 | }) + 'Z' |
| 82 | ) |
| 83 | ); |
| 84 | }; |
| 85 | |
| 86 | /** |
| 87 | * Adds padding to a time value so |
no test coverage detected