formatDuration
function in meocord/common Since 4.3.0
formatDuration(
ms: number,
target?: Interaction | Message | Locale | `${Locale}`,
options?: FormatDurationOptions,
): stringWrites 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
| Name | Type |
|---|---|
ms | number |
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, | |
options.largest? | DurationUnit |
The largest unit shown: | |
options.smallest? | DurationUnit |
The smallest unit shown: | |
options.round? | 'down' | 'up' | 'nearest' |
How the value is rounded at the smallest unit shown: | |
options.style? | 'narrow' | 'long' | 'param' |
| |
options.t? | Translator<any> |
The translator, for a | |
Returns
stringThe duration in words.
Throws
RangeError when
msis negative,NaNor infinite, or pastNumber.MAX_SAFE_INTEGERin theparamstyle,unitsisn't a whole number of at least 1 orInfinity, a unit isn't one ofw,d,h,m,sandms, orsmallestis larger thanlargest.
Examples
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