1.0.2 ⢠Published 8 months ago
js-time-conversion v1.0.2
ā³ Time Converter (toMilliseconds & fromMilliseconds)
A simple and lightweight npm package to convert time strings to milliseconds and convert milliseconds back into readable formats.
š Features:
- Convert time strings like
"2h","30m","45s","1.5d"into milliseconds. - Convert milliseconds into human-readable time formats.
- Works with floating-point values (
"1.5h"ā5400000ms). - Lightweight with zero dependencies.
š¦ Installation
You can install the package using npm:
npm install js-time-conversionOr using Yarn:
yarn add js-time-conversionš§ Usage
Import the package in your JavaScript/Node.js project:
const { toMilliseconds, fromMilliseconds } = require("js-time-conversion");Convert Time Strings to Milliseconds
console.log(toMilliseconds("2h")); // 7200000
console.log(toMilliseconds("30m")); // 1800000
console.log(toMilliseconds("45s")); // 45000
console.log(toMilliseconds("1.5d")); // 129600000Convert Milliseconds to Readable Time Format
console.log(fromMilliseconds(7200000)); // "2h"
console.log(fromMilliseconds(1800000)); // "30m"
console.log(fromMilliseconds(45000)); // "45s"
console.log(fromMilliseconds(129600000)); // "1.5d"š API Reference
toMilliseconds(timeString)
Converts a time string to milliseconds.
| Parameter | Type | Description | Example |
|---|---|---|---|
timeString | string | Time string with unit (s, m, h, d) | "2h" ā 7200000 |
- Throws an error if the input format is invalid.
fromMilliseconds(ms)
Converts milliseconds to a human-readable time format.
| Parameter | Type | Description | Example |
|---|---|---|---|
ms | number | Milliseconds to be converted | 7200000 ā "2h" |
šØ Error Handling
If an invalid format is provided, the function throws an error:
console.log(toMilliseconds("xyz")); // ā Error: Invalid time format. Use '1s', '2m', '3h', '1.5d'.š ļø Running Tests
To test the package, create a file test.js and run:
const { toMilliseconds, fromMilliseconds } = require("./index");
// Example tests
console.log(toMilliseconds("2h") === 7200000); // true
console.log(fromMilliseconds(7200000) === "2h"); // trueRun the test:
node test.jsš Contributing
Want to improve this package? Feel free to fork and submit a pull request.
- Clone the repository:
git clone https://github.com/Th85534/npm-packages.git - Make changes and push to a new branch.
- Submit a Pull Request!
š License
This package is licensed under the MIT License.