Stop writing manual duration formatting code. Instead, leverage the new powerful Intl.DurationFormat API for internationalized time displays
Trevor I. Lasn ·
· Updated · 3 min read
Building 0xinsider.com, the intelligence layer for prediction markets. Discover what's moving, see who's behind it, and find the edge before the crowd.
Time durations appear everywhere - video players showing remaining time, fitness apps tracking workout lengths, or project management tools measuring task completion time. Formatting these durations consistently across different locales has traditionally required custom code or external libraries.
The Intl.DurationFormat object solves this problem elegantly. It’s part of ECMAScript’s core language specification - specifically the ECMAScript Internationalization API (ECMA-402). This makes it a native JavaScript feature rather than a web browser API, though browser implementation determines its availability.
At its core, Intl.DurationFormat takes a duration object containing time units and formats it according to locale-specific rules. The basic usage is straightforward.
The duration object accepts multiple time units: years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, and nanoseconds. This flexibility allows you to represent any time span from nanoseconds to centuries.
The locale parameter determines how the duration appears based on language and regional conventions. English might use “and” before the final unit, while French employs “et” - these nuances happen automatically:
The output style can be customized through the options parameter. Three primary styles exist: ‘long’, ‘short’, and ‘narrow’. Each provides progressively more compact representations:
To wrap up this article, here’s a final example with all the possible duration units. It demonstrates the full range of time units and how Intl.DurationFormat handles them.
This article was originally published on https://www.trevorlasn.com/blog/intl-durationformat-javascript-time-durations-with-locale-support. It was written by a human and polished using grammar tools for clarity.