msfmt
Version:
A tiny JavaScript library for parsing and formatting milliseconds into human-readable strings
86 lines (61 loc) • 2.89 kB
Markdown
# msfmt
A tiny JavaScript library for parsing and formatting milliseconds into human-readable strings.
[](https://badge.fury.io/js/msfmt)
[](https://coveralls.io/github/OpenDevsFlow/msfmt)
## Installation
```bash
npm install msfmt@latest
````
## Usage
```javascript
const msfmt = require('msfmt');
/* import msfmt from "msfmt";*/
// Parsing
console.log(msfmt('1s')); // 1000
console.log(msfmt('10 seconds')); // 10000
console.log(msfmt('2.5h')); // 9000000
console.log(msfmt('1d')); // 86400000
console.log(msfmt('100')); // 100 (milliseconds)
// Formatting (Short format)
console.log(msfmt(1000)); // 1s
console.log(msfmt(60000)); // 1m
console.log(msfmt(3600000)); // 1h
console.log(msfmt(86400000)); // 1d
console.log(msfmt(500)); // 500ms
console.log(msfmt(0)); // 0
console.log(msfmt(0.1)); // <1ms
// Formatting (Long format - using the { long: true } option)
console.log(msfmt(1000, { long: true })); // 1 second
console.log(msfmt(120000, { long: true })); // 2 minutes
console.log(msfmt(5400000, { long: true })); // 1 hour 30 minutes
console.log(msfmt(86400000*2, { long: true })); // 2 days
console.log(msfmt(500, { long: true })); // 500 ms
console.log(msfmt(0, { long: true })); // 0 ms
```
## API
```typescript
msfmt(value: string | number, options?: { long?: boolean }): number | string;
```
* `value`: The value to parse or format. Can be a string (e.g., "1s", "10 minutes") or a number (milliseconds).
* `options`: An optional object with the following property:
* `long`: A boolean value. If `true`, the output will be in a longer, more human-readable format (e.g., "1 second" instead of "1s"). Defaults to `false`.
**Parsing behavior**
* Accepts strings like "1ms", "1 s", "10 seconds", "2.5h", "1d", "1 week", "1 year".
* Case-insensitive for units (e.g., "Ms", "SECONDS").
* Returns the duration in milliseconds as a number.
* Throws an error if the input string is invalid.
**Formatting behavior**
* Formats milliseconds into short strings like "1s", "1m", "1h", "1d", "500ms".
* With the `long` option, formats into longer strings like "1 second", "2 minutes", etc.
* Handles pluralization correctly.
* Returns "0" for 0 milliseconds in short format and "0 ms" in long format.
* Returns "\<1ms" for values between 0 and 1ms in short format.
## Contributing
Contributions are welcome\! Please open an issue or submit a pull request.
## License
Apache-2.0
## Acknowledgements
This package was inspired by the popular `ms` package, but provides both parsing and formatting functionality.
## Support
**For help or support, join our community on Discord.**
[](https://discord.gg/OpenDevsFlow/6UGYjhSS5v)