durationly
v1.2.0
Published
Parse and format human durations: '2h 30m' <-> 9000000. Compound units, ISO 8601, typed strings, i18n. Zero dependencies.
Maintainers
Readme
durationly
Turn duration text into milliseconds and milliseconds back into text: '2h 30m' <-> 9000000.
durationly reads durations like '30s', '2h 30m' or '1 day and 4 hours' and gives you milliseconds. It also turns milliseconds into short or long text for people to read. Use it for timeouts and TTLs in config files, for showing elapsed time, or as a replacement for ms.
Features
- Compound durations:
'1d 4h 30m','1h30m','1 hour, 30 minutes','1 hour and 30 minutes'. - Both directions: parse strings to milliseconds, format milliseconds to text.
- Typos are caught early:
'5 minuts'is a TypeScript error, and at runtime the error says Did you mean 'minute'? - ISO 8601 (the standard duration format used by many APIs):
'PT2H30M'in,toISO()out. - Any language:
format(ms, { locale: 'es' })gives'2 horas y 30 minutos', using the built-inIntlAPI. - Exact output:
9000000formats as'2h 30m', not a rounded'3h'. UsemaxUnitswhen you want it shorter. - Zero dependencies, about 2.5 KB gzipped, ESM and CommonJS, works in Node.js, Bun, Deno and browsers.
Installation
npm install durationlypnpm add durationly
yarn add durationly
bun add durationlyQuick start
import durationly from 'durationly'
// Text to milliseconds
durationly('2h 30m') // => 9000000
durationly('1 day and 4 hours') // => 100800000
durationly('PT1M30S') // => 90000
// Milliseconds to text
durationly(9000000) // => '2h 30m'
durationly(9000000, { long: true }) // => '2 hours 30 minutes'
durationly.format(5430000, { maxUnits: 1 }) // => '2h'
// Invalid input throws an error with a hint
durationly('5 minuts')
// => throws DurationError: Unknown unit 'minuts' in duration '5 minuts'. Did you mean 'minute'?With CommonJS, use const durationly = require('durationly'). Named exports work too: const { parse, format } = require('durationly').
Table of contents
Usage
Read timeouts from environment variables
Config values often come as text. Parse them once at startup. A bad value throws right away, so you find the problem before the first request.
import durationly from 'durationly'
// CACHE_TTL=5m, REQUEST_TIMEOUT="1m 30s"
const cacheTtl = durationly(process.env.CACHE_TTL ?? '5m') // => 300000
const requestTimeout = durationly(process.env.REQUEST_TIMEOUT ?? '30s') // => 90000
setTimeout(retry, durationly('30s'))
redis.set(key, value, 'PX', cacheTtl)You can write durations in many ways. Units are not case-sensitive, and you can mix them:
durationly('90s') // => 90000
durationly('1.5h') // => 5400000
durationly('2 Hours') // => 7200000
durationly('1hour30min') // => 5400000
durationly('1 hour, 30 minutes') // => 5400000
durationly('500') // => 500 (a plain number means milliseconds)
durationly('-1h 30m') // => -5400000 (the sign applies to the whole duration)| Unit | Spellings |
|---|---|
| Milliseconds | ms, msec, msecs, millisecond, milliseconds |
| Seconds | s, sec, secs, second, seconds |
| Minutes | m, min, mins, minute, minutes |
| Hours | h, hr, hrs, hour, hours |
| Days | d, day, days |
| Weeks | w, wk, wks, week, weeks |
| Months | mo, month, months |
| Years | y, yr, yrs, year, years |
A year is 365.25 days and a month is 1/12 of a year, the same as in ms.
Show elapsed time to users
format() turns milliseconds into text. By default it shows every unit from days down to milliseconds, and skips units that are zero.
import { format } from 'durationly'
const start = performance.now()
await runJob()
console.log(`Done in ${format(performance.now() - start, { maxUnits: 2 })}`)
// for example: 'Done in 1s 834ms'
format(90061001) // => '1d 1h 1m 1s 1ms'
format(90061001, { maxUnits: 2 }) // => '1d 1h'
format(9000000, { long: true }) // => '2 hours 30 minutes'
format(119500, { smallest: 'second' }) // => '2m'
format(1209600000, { units: ['week', 'day'] }) // => '2w'
format(9000000, { separator: ', ', long: true }) // => '2 hours, 30 minutes'maxUnitskeeps only the largest units. The last unit shown is rounded:format(5430000, { maxUnits: 1 })gives'2h'.smallesthides smaller units and rounds into the smallest one you keep.unitspicks which units to use. Weeks, months and years are used only when you list them here.
Show durations in the user's language
Pass locale to format with the Intl API that is built into JavaScript. Long unit names are the default; set style for shorter ones.
format(9000000, { locale: 'en' }) // => '2 hours, 30 minutes'
format(9000000, { locale: 'es' }) // => '2 horas y 30 minutos'
format(9000000, { locale: 'hi' }) // => '2 घंटे और 30 मिनट'
format(9000000, { locale: 'en', style: 'short' }) // => '2 hr 30 min'
format(9000000, { locale: 'de', separator: ' ' }) // => '2 Stunden 30 Minuten'The exact words come from the Intl data in your runtime, so they can differ a little between versions.
Handle invalid input
parse() and durationly() throw a DurationError for invalid input. The message explains the problem and suggests a fix for typos. Use tryParse() or isDuration() when you do not want an error.
import { parse, tryParse, isDuration, DurationError } from 'durationly'
try {
parse('2 hourz')
} catch (error) {
error instanceof DurationError // => true
error.message // => "Unknown unit 'hourz' in duration '2 hourz'. Did you mean 'hour'?"
error.input // => '2 hourz'
}
tryParse('nope') // => undefined
tryParse('5m') // => 300000
isDuration('5m') // => true
isDuration('abc') // => falseUse ISO 8601 durations
ISO 8601 durations look like 'PT2H30M' (2 hours 30 minutes). parse() reads them, and toISO() writes them.
import { parse, toISO } from 'durationly'
parse('PT2H30M') // => 9000000
parse('P1DT12H') // => 129600000
toISO(9000000) // => 'PT2H30M'
toISO('1d 12h') // => 'P1DT12H'
toISO(1500) // => 'PT1.5S'Convert to seconds, minutes or hours
Many APIs want seconds, not milliseconds. For example, the HTTP Cache-Control header and the JWT exp claim.
import { toSeconds, toMinutes, toHours } from 'durationly'
res.setHeader('Cache-Control', `max-age=${toSeconds('1h')}`) // max-age=3600
toSeconds('15m') // => 900
toMinutes('1h 30m') // => 90
toHours('1d 12h') // => 36Get a date in the future or in the past
import { fromNow, ago } from 'durationly'
const expiresAt = fromNow('7d') // a Date one week from now
const since = ago('2h') // a Date two hours ago
fromNow('1h', new Date('2025-01-01T00:00:00Z')).toISOString()
// => '2025-01-01T01:00:00.000Z'Catch typos with TypeScript
Duration string literals are checked at compile time. Values typed as plain string, such as env vars or config files, are accepted and checked at runtime.
import durationly, { type Duration } from 'durationly'
durationly('2h 30m') // OK
durationly('2 hourz') // compile error
durationly(process.env.TTL!) // OK, checked at runtime
interface Config { timeout: Duration } // number | '30s' | ...API
All functions are named exports. They are also properties of the default export, for example durationly.format().
durationly(input, options?)
function durationly(input: string): number
function durationly(input: number, options?: FormatOptions): stringThe default export. A string is parsed to milliseconds, like parse(). A number is formatted to text, like format(), with the same options. Throws DurationError for invalid input.
parse(input)
function parse(input: string | number): numberParses a duration and returns milliseconds. A number is returned as it is. Accepts compound durations, ISO 8601 durations and plain numbers (milliseconds). Throws DurationError for invalid input, for numbers that are not finite (NaN, Infinity) and for strings longer than 200 characters.
tryParse(input)
function tryParse(input: unknown): number | undefinedLike parse(), but returns undefined instead of throwing.
isDuration(input)
function isDuration(input: unknown): input is DurationReturns true if parse() would accept the value.
format(input, options?)
function format(input: Duration | string, options?: FormatOptions): stringFormats milliseconds (or a duration string) as text. Negative durations start with -. Zero formats as '0ms'.
| Option | Type | Default | Description |
|---|---|---|---|
| long | boolean | false | Use long unit names: '2 hours 30 minutes' instead of '2h 30m'. |
| maxUnits | number | no limit | Show at most this many units. The last one is rounded. |
| units | UnitName[] | ['day', 'hour', 'minute', 'second', 'millisecond'] | Units to use, largest first. An unknown unit throws DurationError. |
| smallest | UnitName | 'millisecond' | Smallest unit to show. Smaller remainders are rounded into it. |
| separator | string | ' ' | Text between parts. With locale, it replaces the list format of the language. |
| locale | string \| string[] | none | Format with Intl for this language, for example 'es'. Uses long names unless style is set. |
| style | 'long' \| 'short' \| 'narrow' | 'long' | How Intl writes unit names. Only used with locale. |
UnitName is one of 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond'.
toISO(input)
function toISO(input: Duration | string): stringFormats a duration as an ISO 8601 string, such as 'PT2H30M'. It uses only days, hours, minutes and seconds (with decimals), so the value converts back exactly with parse().
toMilliseconds, toSeconds, toMinutes, toHours, toDays, toWeeks
function toSeconds(input: string | number): numberParse a duration and return it in the named unit. All six have the same signature. The result can have decimals: toDays('36h') returns 1.5.
fromNow(input, from?) and ago(input, from?)
function fromNow(input: string | number, from?: Date | number): Date
function ago(input: string | number, from?: Date | number): DateReturn a Date that is the duration after (fromNow) or before (ago) from. from is a Date or a timestamp in milliseconds. The default is now.
UNITS
const UNITS: Readonly<Record<UnitName, number>>The length of each unit in milliseconds, for example UNITS.hour is 3600000. The object is frozen (read-only).
DurationError
class DurationError extends TypeError {
readonly input: unknown
}Thrown for invalid input. The bad value is in error.input.
Types
All types are exported:
Duration: a number of milliseconds or a duration string. Use it to type config objects.DurationString: the general shape of a duration string.FormatOptions: the options offormat().UnitName,Unit,ShortUnit: unit names and every accepted spelling.CheckDuration<T>,IsValidDuration<T>: the compile-time checks for string literals.Durationly: the type of the default export.
Comparison
| | ms | durationly |
|---|---|---|
| '2h' | Yes | Yes |
| '2h 30m' / '1h30m' | No (returns undefined) | Yes |
| '1 hour and 30 minutes' | No | Yes |
| ISO 8601 ('PT2H30M') | No | Yes |
| Format 9000000 | '3h' (rounded) | '2h 30m' (exact, or shorter with maxUnits) |
| Invalid input | Returns undefined without an error | Throws a clear error (or use tryParse) |
| Typos caught at compile time | No | Yes |
| Output in other languages | No | Yes, with Intl |
Migrating from ms
For parsing, the change is one line:
// Before
import ms from 'ms'
ms('2h') // => 7200000
// After
import durationly from 'durationly'
durationly('2h') // => 7200000Differences to know:
msreturnsundefinedfor invalid input.durationlythrows aDurationError. UsetryParse()if you wantundefined.ms(9000000)returns'3h'.durationly(9000000)returns'2h 30m'. Add{ maxUnits: 1 }for one rounded unit:durationly(9000000, { maxUnits: 1 })returns'3h'.ms(60000, { long: true })becomesdurationly(60000, { long: true }). Both return'1 minute'.- Years (365.25 days) have the same length in both packages.
Notes and limitations
- Months and years have a fixed length. A year is 365.25 days and a month is 1/12 of that. They do not follow the calendar:
format(durationly('1 month'))gives'30d 10h 30m'. format()does not use weeks, months or years by default.format(1209600000)gives'14d'. List the units inunitsto use them.- Only the whole duration can have a sign.
'-1h 30m'is -1.5 hours.'1h -30m'throws. - Compile-time checks work only for string literals. Values typed as
stringare checked at runtime. - Text from
localecomes from your runtime'sIntldata. It can differ a little between runtimes and versions. IfIntl.ListFormatis missing, parts are joined with spaces.
Requirements
- Node.js 18 or newer. Also works in Bun, Deno and browsers.
- ESM and CommonJS.
- TypeScript types included.
- Zero dependencies.
License
MIT
