Intl.DurationFormat Formats Elapsed Durations
Turn duration objects into locale wording with Intl.DurationFormat: default, long, digital styles, other locales, and sparse spans with partial units.
Code
// Intl.DurationFormat 把时长对象 (elapsed durations) 渲染成各语言习惯的文案
const span = { hours: 1, minutes: 30, seconds: 5 };
const en = new Intl.DurationFormat('en');
console.log('en default:', en.format(span));
console.log('en long :', new Intl.DurationFormat('en', { style: 'long' }).format(span));
console.log('en digital:', new Intl.DurationFormat('en', { style: 'digital' }).format(span));
console.log('en narrow :', new Intl.DurationFormat('en', { style: 'narrow' }).format(span));
// 其他 locale:德语与中文的单位词序、连接词完全不同
console.log('de default:', new Intl.DurationFormat('de').format(span));
console.log('zh default:', new Intl.DurationFormat('zh').format(span));
// 稀疏时长:只提供出现的单位
console.log('partial :', en.format({ minutes: 42 }));Output
Captured from a sandboxed run of this snippet in the build pipeline.
en default: 1 hr, 30 min, 5 sec
en long : 1 hour, 30 minutes, 5 seconds
en digital: 1:30:05
en narrow : 1h 30m 5s
de default: 1 Std., 30 Min. und 5 Sek.
zh default: 1小时30分钟5秒
partial : 42 minInside the snippet
Everything operates on top-level bindings: span, en.
The top-level object literal pins hours, minutes, seconds as plain values — no derivation, no imports behind them.
Putting it to use
The demo output is labeled (en default:, en digital:, en narrow :), so every printed line maps back to its originating operation.
Core lines
const en = new Intl.DurationFormat('en');
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `span`, `en`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.