@sanely/duration
v0.1.0
Published
Parse human-readable time expressions into any unit, and format durations into human-readable strings
Maintainers
Readme
@sanely/duration is a TypeScript package for time expressions. It converts "1h" to seconds, parses "1h 30m" to milliseconds, and formats 5_400_000 as "1h 30m".
Features
- Unit functions convert one time expression, such as
seconds("1h")anddays("1w"). convert("1h 30m", "minutes")converts a compound time expression to a named unit.parseconverts a compound time expression to milliseconds.formatwrites milliseconds as a short-form or long-form time expression.- The unit functions check string literals at compile time, and give the reason for an invalid one.
- Each result is a
Durationin its unit, soformat(seconds("1h"))is a type error. isTimeExpressionandisValidTimeExpressioncheck values at run time.- Invalid input throws
InvalidTimeExpressionError, orsafeParsereturnsnull. - Every export is a named export that a bundler can remove when you do not use it.
- No external dependencies.
Install
npm install @sanely/durationThe package needs Node.js 20 or later.
Get started
import { convert, format, ms, parse, seconds } from "@sanely/duration"
seconds("1h") // 3600
ms("30s") // 30_000
convert("1h 30m", "minutes") // 90
parse("1h 30m") // 5_400_000
format(5_400_000, { precision: 2 }) // "1h 30m"Documentation
How-to guides:
- How to validate a time expression from user input
- How to format a duration for display
- How to pass a duration to an API that takes a number
Reference:
Explanation:
Contributing
Read the architecture, testing guide, and root contributor guide before changing the package.
License
MIT. See LICENSE.
