'Intl.DateTimeFormat inconsistent between Chrome/Node and Firefox
Given the following code:
const foo = new Intl.DateTimeFormat('en-GB', {
hourCycle: 'h12',
timeStyle: 'short',
dateStyle: 'short',
}).format(1650442310319);
The output in Chrome/Node is 20/04/2022, 09:11 am whilst the output in Firefox is 20/04/2022, 9:11 am. Notice the leading 0 on the hour being inconsistent.
One way to fix this for this en-GB locale is:
const bar = new Intl.DateTimeFormat('en-GB', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
hourCycle: 'h12',
hour: 'numeric',
minute: '2-digit',
}).format(1650442310319);
Now the output in both browsers is 20/04/2022, 9:11 am. However, this breaks formatting by locale. For example if I switch to en-US, the string we'd want is 4/20/2022, 9:11 am but we actually get 04/20/2022, 9:11 am because we specified 2 digits for the day and month.
It looks like the ideal solution would be to combine the approaches, such as:
const foo = new Intl.DateTimeFormat('en-GB', {
hourCycle: 'h12',
hour: 'numeric',
minute: '2-digit',
dateStyle: 'short',
}).format(1650442310319);
But alas this is not possible. As the MDN docs say:
Note: dateStyle can be used with timeStyle, but not with other options (e.g. weekday, hour, month, etc.).
So is there any way to use this native datetime formatter consistently, without sacrificing the benefits of formatting by locale, which is one of the primary purposes of it?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
