Skip to main content

Localize Durations Like 1 hr 5 min Without Hand-Built Unit Strings

2026-11-17

Localize Durations Like 1 hr 5 min Without Hand-Built Unit Strings

Your workout summary says "1 hr 5 min", your player shows "3:07", and your snooze menu offers "1 day". In English, all three look finished. Switch the app to German and the hand-built helper still prints "hr" and "min". Switch to Spanish and a "proper" formatter offers "uno día". Turn on VoiceOver and "1:05" sounds like a time of day. Duration formatting is locale data plus a handful of decisions your code has to make on purpose: which units to show, which pattern to use, which locale to pass, and what a screen reader should hear. This guide shows how to replace hand-built strings with platform formatters on iOS, Android, and the web, and how to test the result before release.

It assumes you already format absolute dates and numbers with locale-aware APIs, as covered in our guide to localizing app dates, times, and numbers, and that you have sorted out unit systems for distance and weight, as covered in localizing measurement units. Durations need their own handling, because unit names, word order, separators, and grammar change by locale even though an hour lasts the same everywhere.

The short answer

  1. Keep durations as numbers (seconds, a Swift Duration, or a JavaScript duration object) and format them only at the edge of the UI.
  2. Pick a presentation per surface: a unit list such as "1 hr, 5 min" for summaries, a positional pattern such as "1:05:00" for running timers.
  3. Call the platform duration formatter and pass the locale your app resolved, not whatever the device happens to use.
  4. Use translator-owned strings for fixed menu choices, and give positional durations a spelled-out accessibility label.
  5. Test zero, rounding, and unit-boundary values across a small set of locales, and never assert exact formatter output in tests.

Why hand-built duration strings fail

The common helper divides seconds by 60, pads with zeros, and joins the parts with a colon or with English suffixes. A 2026 issue on the Spotiglass project shows the pattern clearly: track durations were built as "\(totalSeconds / 60):\(String(format: "%02d", totalSeconds % 60))" in two places, the --:-- placeholder for unknown lengths was a raw literal outside the string catalog, and the display string was later split on : to recover milliseconds. The issue's expected behavior and acceptance criteria ask for one shared locale-aware formatter and for numbers to be carried as numbers instead of re-parsed from display text. Carrying numbers as numbers protects you later: once a display string becomes data, every locale change becomes a parsing bug.

Unit names are the second trap. "hr" and "min" are English abbreviations, and the number does not always come first. The web.dev Baseline announcement shows the same duration rendered in Swahili as "mwaka 1, saa 20, dakika 15 na sekunde 35", with each unit word before its number, and in Chinese with no spaces at all. Plural forms differ too, and so does the word that joins the last two units. A string template with a number slot and an English suffix cannot cover any of that.

Positional patterns have the same problem. Unicode CLDR treats them as locale data: LDML Part 2 defines durationUnit patterns such as h:mm:ss per locale, separately from clock-time formats. Hard-coding %d:%02d skips that data and also skips locale digits.

Use the platform duration formatter

Every major platform ships a locale-aware duration formatter. Your job is to choose the right one for your deployment target and give it the right locale.

iOS and macOS

On iOS 16 and later, format a Swift Duration with Duration.UnitsFormatStyle, which Apple describes as showing durations "with localized labeled components", or with Duration.TimeFormatStyle for a "compact, localized format with separators".

let appLocale = Locale(identifier: selectedLanguageTag) // the app's resolved language
let elapsed = Duration.seconds(3_900)

let summary = elapsed.formatted(
    .units(allowed: [.hours, .minutes], width: .abbreviated)
    .locale(appLocale)
)

let timer = elapsed.formatted(
    .time(pattern: .hourMinuteSecond)
    .locale(appLocale)
)

Read the defaults before you rely on them. The swift-foundation source for units(...) allows hours, minutes, and seconds by default, uses the abbreviated width, hides zero-value units, and hides fractional parts. Hiding zeros is usually what you want for "1 hr" but not for a split table where every row should show the same units. The same source documents a fractional-part strategy that can show 1 hour 15 minutes as "1.25 hr" when hours is the only allowed unit.

For older deployment targets, DateComponentsFormatter has been available since iOS 8. Its UnitsStyle values run from spelled out ("nine hours, forty-one minutes, thirty seconds") through full ("9 hours, 41 minutes, 30 seconds"), short ("9 hr, 41 min, 30 sec"), brief, and abbreviated ("9h 41m 30s") to positional. Apple also documents that one configured instance can be shared across threads as long as you do not change its configuration while another thread is using it, so build one formatter per style and locale and reuse it.

Set the locale on purpose

Per-app language settings expose one specific bug. Set the formatter's locale from the app's selected language, because DateComponentsFormatter follows the device language unless its calendar locale is set explicitly.

A developer with a Danish-only app reported that DateComponentsFormatter kept returning "1 yr" on English devices, even after writing AppleLanguages in code. The top answer gives the formatter a calendar whose locale is Danish, and it warns that the "About" approximation phrase may still not be translated. Resolve the app's language once, build a Locale from it, and pass it to every formatter. On DateComponentsFormatter that means formatter.calendar = calendarWithAppLocale. On Duration styles it means .locale(appLocale). If you rely on approximation or "remaining" phrases, check them in each shipped language, or keep that wording in your own translated string. This matters most for apps with an in-app language picker or iOS per-app language settings, where device and app language legitimately differ.

Android

Android has two very different tools. DateUtils.formatElapsedTime produces only "MM:SS" or "H:MM:SS", described as the form used on the call-in-progress screen, and it takes no locale parameter. It is fine for a running call or stopwatch shown in the default locale. It cannot produce "1 hr 5 min".

For unit lists, use ICU's MeasureFormat, available from API 24, with an explicit locale:

val appLocale: Locale = resolvedAppLocale() // from AppCompatDelegate or your own setting
val fmt = MeasureFormat.getInstance(appLocale, MeasureFormat.FormatWidth.SHORT)

val text = fmt.formatMeasures(
    Measure(1, MeasureUnit.HOUR),
    Measure(5, MeasureUnit.MINUTE)
)

formatMeasures joins the parts with the locale's unit-list pattern, so call it once with every unit instead of formatting each unit and concatenating the results yourself. One Android developer, finding that RelativeDateTimeFormatter only speaks in past or future tense, concatenated two MeasureFormat results with a space and noted that passing both measures to one call gives "1 minute, 30 seconds" instead. Prefer the single call. The documentation adds three more details. Zero values are printed ("3 feet, 0 inches"), so drop zero units before you call it. You are responsible for passing units in descending order. And FormatWidth.NUMERIC turns an hour, minute, and second sequence into "5:37:23" instead of "5h, 37m, 23s", which gives you a locale-aware positional timer that does accept a locale. Android describes MeasureFormat as kept for backwards compatibility and encourages new users to check whether ICU NumberFormatter fits first; for multi-unit duration lists, formatMeasures is the documented tool.

Avoid the shortcuts found in older answers. A widely viewed question on formatting durations with localized units on Android collected answers ranging from a custom library to reading private android framework string resources by name. Those resource names are not public API and can change between releases.

Web and cross-platform code

On the web, Intl.DurationFormat has been Baseline since March 2025, after the TC39 proposal reached Stage 4 in December 2024. The constructor takes a locale and a style of long, short (the default), narrow, or digital, plus per-unit style and display options.

const fmt = new Intl.DurationFormat(appLocaleTag, { style: "short" });
fmt.format({ hours: 1, minutes: 5 });

const timer = new Intl.DurationFormat(appLocaleTag, { style: "digital" });
timer.format({ hours: 1, minutes: 5, seconds: 0 });

Pass the app's language tag explicitly. If you pass undefined, the runtime default is used, which is the browser language, not your account setting. Google Chrome's guidance on human-readable durations recommends feature detection with typeof Intl.DurationFormat !== "undefined", lists support from Chrome 129, Firefox 136, and Safari 16.4, and warns against showing Temporal.Duration.toString() to users because it returns ISO 8601 strings such as PT1H30M. It also shows round({ largestUnit: "hours" }) for turning 90 minutes into 1 hour 30 minutes, although Temporal itself is still missing from Safari according to the same guide.

TypeScript projects can trip before runtime does. An Angular 21 developer reported Property 'DurationFormat' does not exist on type 'typeof Intl' in May 2026; the answer says the definitions arrived in TypeScript 6.0 while Angular 21 pinned an earlier version, and suggests copying the type declarations or using a polyfill. The TypeScript issue for the missing definitions was open from November 2024 until February 2026. Check your compiler version before you plan the migration.

Keep fixed choices in translator-owned strings

Formatters are built for computed values. Menu choices are a different case. Do not use spelled-out duration styles for fixed picker choices, because spelled-out numbers do not agree with the noun's gender and produce labels such as uno día; use numeric unit styles or translator-owned strings instead.

The evidence is a September 2026 bug in the Santa macOS security agent. Its notification-silence picker used DateComponentsFormatter with .spellOut, and the issue report lists the output by language: Spanish "uno día", "uno semana", and "uno mes"; German "eins Tag"; French "un semaine"; Russian "один неделя". The reporter traced it to the formatter spelling the standalone cardinal without gender agreement, which means no translation file could fix it. The proposed fixes were the numeric .full style or explicit localized strings per option, and the reporter warned that a Spanish-only patch would leave the other languages broken.

The decision rule that follows:

  • If the value is computed (a workout length, a remaining time, a track length), use a numeric unit style from the formatter.
  • If the value is one of a few fixed options ("1 hour", "1 day", "1 week"), make each option a translatable string with a plural-aware key, so translators can write "un día" and "eine Woche" directly.
  • If design wants spelled-out numbers, put them in the translated string. Do not ask the formatter to spell them.

This is also where a translation workflow helps. The strings around a duration ("Snooze for %@", "%@ left", "Finished in %@") still need placeholders that translators can move, as explained in stop concatenating strings. i18nAgent translates those message strings and checks placeholders and plural forms; the duration itself should still come from the platform formatter at runtime.

Choose units and rounding before formatting

Many visible duration bugs come from unit and rounding rules. Decide these rules per surface, write them down, and share them with design and localization:

  • Largest and smallest unit. A workout summary might allow hours and minutes; a timer needs seconds; a delivery ETA might show minutes only. Use allowed units on Swift styles, the duration object fields on the web, and the measures you pass on Android.
  • Maximum unit count. Swift's maximumUnitCount and an equivalent rule in your Android and web code keep "1 day, 3 hr, 12 min, 4 sec" from appearing in a card that has room for two parts.
  • Rounding direction. Remaining time should usually round up, so the UI never says "0 min left" while time remains. Elapsed time usually rounds down.
  • Zero handling. Decide whether zero units are hidden. Swift hides them by default, Android's formatMeasures prints them, and the web lets you choose per unit with display options. Normalize this yourself so platforms agree.
  • Balancing. Convert 90 minutes to 1 hour 30 minutes before formatting if that is the rule, and do it once in shared code.

Make durations accessible

Positional output is compact, and that is why it is ambiguous. Give positional durations such as 1:05 a spelled-out accessibility label, because a colon pattern can be heard as a clock time and does not say whether it means hours or minutes.

This is a recommendation based on how the patterns work rather than a documented platform rule. Swift's .hourMinute and .minuteSecond patterns both produce a number, a colon, and two digits, so "1:05" can be 1 hour 5 minutes or 1 minute 5 seconds depending on which pattern produced it. An iOS developer asking how to make formatted times sound natural in VoiceOver was pointed to building the accessibility label from a spelled-out DateComponentsFormatter instead of the visible string, and a SwiftUI duration-formatting guide notes in one line that unit styles are usually more accessible. In practice:

  • Keep the compact visible text for the running timer.
  • Set accessibilityLabel (iOS) or contentDescription (Android) to a full unit style such as "1 hour, 5 minutes" in the app's locale.
  • On the web, use aria-label or visually hidden text built with Intl.DurationFormat and style: "long".
  • Throttle updates to that label. A live region that announces every second is noise.

Spelled-out styles are acceptable in a screen-reader label because the reader needs the meaning there, but keep the Santa failure in mind: check gender agreement in each language before you ship spelled-out output anywhere.

Test durations before release

Duration output is not a stable string. The MDN page for Intl.DurationFormat.prototype.format() states that output may vary between implementations, may contain non-breaking spaces or bidirectional control characters, and should not be compared to hard-coded constants. Expect the same from ICU and Foundation output as locale data changes with OS updates, and write tests that check behavior:

  • Assert structure with formatToParts() on the web, or compare against the formatter's own output for the same input and locale.
  • Normalize whitespace before any snapshot comparison, and update snapshots deliberately when an OS or ICU version changes.
  • Test boundary values: 0, 59 seconds, 60 seconds, 59 minutes 59 seconds, 60 minutes, 90 minutes, 24 hours, and a negative value if your API can produce one.
  • Run a small locale matrix: en, de, es, ja, ar, and ru cover unit abbreviations, gender agreement, no-space scripts, right-to-left layout with locale digits, and rich plural rules.
  • Run the matrix with the device in one language and the app in another, which is the only way to catch formatters following the system instead of your setting.
  • Add a lint rule or code search for %02d, ":" joins, and string literals such as " min" and " hr" in UI code.

What this guide does not cover

Relative phrases such as "5 minutes ago" describe a point in time and need relative-time formatters, not duration formatters. Ranges between two dates ("Mar 3 to 5") need interval formatting. Both have their own failure modes, and mixing them up is how "in 1 hour 30 minutes" ends up assembled from two APIs.

Next step

Search your codebase for %02d, formatElapsedTime, " min", " hr", and .spellOut. Pick the first hand-built duration you find, replace it with the platform duration formatter using the app's resolved locale, move any fixed picker choices into translated strings, add a spelled-out accessibility label to positional timers, and add the six-locale boundary test with the device and app languages set differently before your next release.