Formatting Timer Readouts with Intl.DurationFormat: What It Does and What It Leaves to You
Most timer readouts are built from padStart(2, "0") and a colon. That works until you want localized digits, or a spoken-friendly string like "25 minutes". Intl.DurationFormat covers both, and MDN labels it Baseline 2025: "Since March 2025, this feature works across the latest devices and browser versions." I tried it on a timer readout and found four places where it does less than you might…
The article discusses the capabilities and limitations of the Intl.DurationFormat API when formatting timer readouts. The API allows for localized digits and spoken-friendly strings, but has four areas where it falls short and one engine difference observed.
Firstly, the format does not carry a passed value of seconds, resulting in a format like 00:125 instead of 02:05. This is why a helper function, splitMs, is required to properly format the data. Second, the formatter displays milliseconds when they are nonzero. If the display only shows seconds, the milliseconds value should be truncated first.
Third, the formatter truncates values instead of rounding them. This means that for a stopwatch, 1.9 seconds would be displayed as 00:01, while for a countdown, 0.9 seconds remaining would display as 00:00, as the last second is truncated.
Fourth, the format requires consistent signs for each field, and only integers are allowed. If mixed signs are provided, a RangeError will be thrown. For example, { minutes: 1, seconds: -5 } will cause an error. To handle overtime, the signs of all fields must be negated, as demonstrated by formatRemaining(-1500).
Lastly, the fractional digits option can be set from 0 to 9, but discrepancies were observed across different engines when setting values between 0 and 3. Chrome 156 showed no mismatches at 0 and 1 digit fractional values, while Node 24.22.1 showed 21 mismatches at 2 digits and 396 mismatches at 3 digits. This inconsistency could lead to unexpected formatting results, making it crucial to test targets or build the fraction manually if displaying hundredths.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to