Unitime - Simplified time units
Unitime is a lightweight JavaScript utility module which provides powerful, human-readable functions for converting various time units. The project was inspired by Java's TimeUnit by Doug Lea.
Human-readable, yet concise
const h ms = ; h`720`; // evaluates to 7ms`3`; // evaluates to 3000000
Installation
npm install unitime
Description
Unitime provides lightweight methods for converting between different units of time with a human-readable syntax. The idea is reducing the mental load caused by interpreting complex time declarations like 24*60*60*1000
or 86400000
which both describe the number of milliseconds in a single day. Using this library you can simply write d(1)
, or d`1`
if you prefer template literals.
Time formats that are currently supported are:
- Nanoseconds (ns)
- Microseconds (us)
- Milliseconds (ms)
- Seconds (s)
- Minutes (min)
- Hours (h)
- Days (d)
You can specify the target format on initialization to make the code even more concise. This is especially useful when writing configuration files in JavaScript:
const d h = const config = duration: d`7` // evaluates to 604800000 interval: h`12` // evaluates to 43200000
The library is written entirely in Typescript.
Usage examples
Convert to a predefined time unit
You can predefine the target unit by using .to(unit)
when initializing:
const ns s = ns`100`; // 0.0001; // 1000000
Convert to any time unit
You can also individually decide the target unit for each variable:
const ns s = ns`100`; // 0.0001; // 1.6666666666666667
License
This work by Jonatan Hamberg is licensed under the MIT License.