Skip to content
GitHub

formatDuration

function in meocord/common Since 4.3.0

formatDuration(
  ms: number,
  target?: Interaction | Message | Locale | `${Locale}`,
  options?: FormatDurationOptions,
): string

Writes a length of time for people, such as 1h 5m or 1 hour, 5 minutes, in the language of the user or server it is for.

It shows units units, largest first: the largest the value reaches, up to largest, and the ones below it down to smallest. The value is rounded to a whole number of the smallest unit shown; when rounding lifts it into a larger unit, the units are chosen again, so 3,599,500 ms rounded up reads 1h, not 59m 60s. A unit whose count is 0 is left out; a value that rounds to 0 reads 0s, in smallest.

An interaction's text is in its user's locale and a message's in its server's, through its app's translator; a Locale names the language, with options.t as the translator. Without a translator or a target the text is MeoCord's English. The unit words are MeoCord's texts in meocord.duration, which an app's catalog translates.

Parameters

NameType
msnumber

The duration in milliseconds: a finite number, at least 0.

target?Interaction | Message | Locale | `${Locale}`

The interaction or message the text is for, or a locale.

options?FormatDurationOptions

How many units, which units, the rounding, the style and the translator.

options.units?number

How many units to show, largest first: 2 unless given, Infinity for every unit down to smallest.

options.largest?DurationUnit

The largest unit shown: 'd' unless given, so ten days read 10d.

options.smallest?DurationUnit

The smallest unit shown: 's' unless given, so 1500 ms reads 1s.

options.round?'down' | 'up' | 'nearest'

How the value is rounded at the smallest unit shown: 'down' unless given.

options.style?'narrow' | 'long' | 'param'

'narrow' (the default) writes 1h 5m; 'long' writes 1 hour, 5 minutes, joined as the locale's catalog joins them; 'param' writes 1h5m, which a {x:duration} param reads back, never translated, for a value up to Number.MAX_SAFE_INTEGER.

options.t?Translator<any>

The translator, for a Locale target or to use another than the target's app's.

Returns

string

The duration in words.

Throws

  • RangeError when ms is negative, NaN or infinite, or past Number.MAX_SAFE_INTEGER in the param style, units isn't a whole number of at least 1 or Infinity, a unit isn't one of w, d, h, m, s and ms, or smallest is larger than largest.

Examples

TypeScript
declare const interaction: ChatInputCommandInteraction

formatDuration(3_900_000) // '1h 5m'
formatDuration(3_900_000, undefined, { style: 'long' }) // '1 hour, 5 minutes'
formatDuration(3_900_000, interaction) // in the interaction's language, through the app's translator
formatDuration(5_400_000, undefined, { style: 'param' }) // '1h30m', which {x:duration} reads back as 5400000