durationx
v1.0.0
Published
Parse and format time durations like a pro. Zero dependencies, tiny footprint.
Maintainers
Readme
durationx
Parse and format time durations like a pro.
Zero dependencies - ~1 KB gzipped - TypeScript - Node + Bun + browser
Why durationx?
Human time strings in, milliseconds out. Milliseconds in, human strings out. No wrappers, no magic, just a tiny parser and formatter that just works.
"1d 2h 30m" -> 90_600_000 ms 90_600_000 ms -> "1d 2h 30m"
"2 hours" -> 7_200_000 ms 7_200_000 ms -> "2h"
"1.5h" -> 5_400_000 ms 5_400_000 ms -> "1h 30m"Install
bun add durationx # or
npm install durationxUsage
import { parse, format } from "durationx";
// Parse — anything humans type
parse("1h"); // 3_600_000
parse("1d 2h 30m"); // 90_600_000
parse("2 hours 15 minutes"); // 8_100_000
parse("1.5h"); // 5_400_000
parse("500ms"); // 500
parse(3600000); // numbers pass through
// Format — anything machines count
format(5_400_000); // "1h 30m"
format(5_400_000, { long: true }); // "1 hour 30 minutes"
format(90_600_000, { maxUnits: 1 }); // "1d"
format(0); // "0ms"
format(-3_600_000); // "-1h"API
parse(input: string | number): number
Parses a human-readable duration into milliseconds. Handles:
| Unit | Aliases | Example |
| ------ | -------------------------------- | --------- |
| years | y, yr, year, years | 1y |
| weeks | w, week, weeks | 2w |
| days | d, day, days | 1d |
| hours | h, hr, hour, hours | 1.5h |
| mins | m, min, minute, minutes | 30m |
| secs | s, sec, second, seconds | 45s |
| millis | ms, milliseconds | 500ms |
- Throws
TypeErroron empty input. - Throws
RangeErrorwhen nothing is recognizable. - Plain numbers (strings or not) pass through untouched.
format(ms: number, options?: FormatOptions): string
Format a millisecond amount into the most compact readable form.
| Option | Type | Default | Description |
| ---------- | --------- | ---------- | ------------------------------------ |
| long | boolean | false | Human words - "1 hour 30 minutes" |
| maxUnits | number | Infinity | Limit the most significant units |
Constants
import { DAY, HOUR, MINUTE, SECOND, WEEK, YEAR } from "durationx";Browser via esm.sh
<script type="module">
import { parse } from "https://esm.sh/durationx";
console.log(parse("30 minutes")); // 1_800_000
</script>Development
git clone https://github.com/knownasrazi/durationx.git
cd durationx
bun install
bun test # run tests
bun run build # tsup -> dist/
bun run lint # biome checkLicense
durationx - built with a stopwatch and good intentions.
