ms
Tiny conversion utility between human time strings like "2 days" and millisecond numbers, used across the Node ecosystem.
Official Documentation ↗v4 (ESM only). Check the official docs for the latest API surface.Installation
npm install mspnpm add msMethods
No methods match this filter.
Tiny conversion utility between human time strings like “2 days” and millisecond numbers, used across the Node ecosystem.
Overview
ms is a two-function library that both parses and formats time spans. Its grammar covers years, weeks, days, hours, minutes, seconds, and raw milliseconds, which covers TTLs, cache max-age values, retry delays, and timeout options.
It powers configuration surfaces across the ecosystem: express session cookies, vercel middleware limits, and jest timeouts all accept strings that ms understands. The long form exists for the reverse trip, turning numbers back into text for human-readable logs.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
ms (parse)— Converts a time string into milliseconds, accepting short forms like “1d” and long forms like “2 days”.ms (format)— Converts a millisecond count into the shortest accurate time string such as “2d” or “1h”.ms (long form)— With long: true the number form returns verbose strings like “2 days” for logs aimed at humans.
Usage Notes
- Use ms in configuration files so operators read “2h” instead of counting zeros in 7200000.
- Treat parse results as possibly undefined and validate user-supplied duration strings at startup.
- Round-trip formatting, ms(ms(“90m”)), is a quick sanity check when parsing external configuration.
Common Pitfalls
- ms never composes units: “1h30m” parses as undefined because the grammar accepts exactly one unit per call.
- Floating-point milliseconds can appear for fractional inputs; keep integer milliseconds when feeding timers.
- In v4 the default export is ESM-only; CommonJS consumers need the v3 line or an import shim.
FAQ
- Why does ms("1m") mean one minute and not one millisecond?
- The unit grammar is fixed: y, w, d, h, m, s and their long forms. Plain digit strings are treated as literal milliseconds, and there is no milli-unit shorthand, so "1m" is always 60000.
- What does ms return for invalid input?
- String parsing returns undefined for anything it cannot recognize, while numbers always format. Check the result before using it in arithmetic, or guard configuration parsing with a fallback.
- How is ms different from dayjs duration?
- ms converts one unit at a time and never does calendar math: "90m" is 5400000 milliseconds, not "1h30m". Use a date library when you need month-aware arithmetic, DST handling, or composed durations.
Report a problem with this API docOpens a pre-filled issue on GitHub.