Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readJavaScript

Format durations with Intl.DurationFormat

Format elapsed time in the user’s locale by splitting a minute count into units and choosing a label or timer style.

Your timer gives you 125 minutes. The label says 2 hr 5 min, and the same component now needs to render in French. A template string makes you own the unit words and the way they join.

Split the number into units

Pass a record of duration units to Intl.DurationFormat. The formatter applies the locale to the units you supply. Split a total into hours and minutes before formatting a label with both units.

Try the examples in Node 24 or a browser that supports the API.

const totalMinutes = 125
const duration = {
  hours: Math.floor(totalMinutes / 60),
  minutes: totalMinutes % 60,
}

for (const locale of ['en-US', 'fr-FR']) {
  const format = new Intl.DurationFormat(locale, { style: 'long' })
  console.log(format.format(duration))
}

The first line reads 2 hours, 5 minutes, and the French line reads 2 heures et 5 minutes.

Use the locale your app uses for the rest of the page. If many rows share that locale and style, create the formatter once and call its format() method for each record. Keep the source value in minutes so sorting, filtering, and edits still operate on the number.

Choose the display shape

For a compact label, try short. For a timer display, pass hours, minutes and seconds and choose digital.

const duration = { hours: 2, minutes: 5, seconds: 0 }

const short = new Intl.DurationFormat('en-US', { style: 'short' })
const digital = new Intl.DurationFormat('en-US', { style: 'digital' })

console.log(short.format(duration))
console.log(digital.format(duration))
console.log(short.format({ minutes: 125 }))

In this locale you get 2 hr, 5 min, 2:05:00 and 125 min. The last call keeps the minutes you supplied.

Exact punctuation and spaces depend on locale data. If you need to style the number and its unit separately, use formatToParts() to keep the separators intact. A test that asserts the formatted label should use a specified locale. Test the minute conversion on its own so a locale data change cannot break the arithmetic test.

Check for typeof Intl.DurationFormat === 'function' if a supported runtime may lack the API. Keep your existing formatter on that path. For fractional totals, decide whether to round to whole minutes or split into seconds before building the duration record.