(locale: string, hourCycle?: DatetimeHourCycle)
| 17 | * locale extension tags or from Intl.DateTimeFormat directly. |
| 18 | */ |
| 19 | export const getHourCycle = (locale: string, hourCycle?: DatetimeHourCycle) => { |
| 20 | /** |
| 21 | * If developer has explicitly enabled 24-hour time |
| 22 | * then return early and do not look at the system default. |
| 23 | */ |
| 24 | if (hourCycle !== undefined) { |
| 25 | return hourCycle; |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * If hourCycle was not specified, check the locale |
| 30 | * that is set on the user's device. We first check the |
| 31 | * Intl.DateTimeFormat hourCycle option as developers can encode this |
| 32 | * option into the locale string. Example: `en-US-u-hc-h23` |
| 33 | */ |
| 34 | const formatted = new Intl.DateTimeFormat(locale, { hour: 'numeric' }); |
| 35 | const options = formatted.resolvedOptions(); |
| 36 | if (options.hourCycle !== undefined) { |
| 37 | return options.hourCycle; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * If hourCycle is not specified (either through lack |
| 42 | * of browser support or locale information) then fall |
| 43 | * back to this slower hourCycle check. |
| 44 | */ |
| 45 | const date = new Date('5/18/2021 00:00'); |
| 46 | const parts = formatted.formatToParts(date); |
| 47 | const hour = parts.find((p) => p.type === 'hour'); |
| 48 | |
| 49 | if (!hour) { |
| 50 | throw new Error('Hour value not found from DateTimeFormat'); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Midnight for h11 starts at 0:00am |
| 55 | * Midnight for h12 starts at 12:00am |
| 56 | * Midnight for h23 starts at 00:00 |
| 57 | * Midnight for h24 starts at 24:00 |
| 58 | */ |
| 59 | switch (hour.value) { |
| 60 | case '0': |
| 61 | return 'h11'; |
| 62 | case '12': |
| 63 | return 'h12'; |
| 64 | case '00': |
| 65 | return 'h23'; |
| 66 | case '24': |
| 67 | return 'h24'; |
| 68 | default: |
| 69 | throw new Error(`Invalid hour cycle "${hourCycle}"`); |
| 70 | } |
| 71 | }; |
| 72 | |
| 73 | /** |
| 74 | * Determine if the hour cycle uses a 24-hour format. |
no outgoing calls
no test coverage detected