1.0.2 • Published 5 months ago

js-time-conversion v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

ā³ Time Converter (toMilliseconds & fromMilliseconds)

A simple and lightweight npm package to convert time strings to milliseconds and convert milliseconds back into readable formats.

npm

šŸš€ 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" → 5400000 ms).
  • Lightweight with zero dependencies.

šŸ“¦ Installation

You can install the package using npm:

npm install js-time-conversion

Or 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")); // 129600000

Convert 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.

ParameterTypeDescriptionExample
timeStringstringTime 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.

ParameterTypeDescriptionExample
msnumberMilliseconds to be converted7200000 → "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"); // true

Run the test:

node test.js

šŸ“Œ Contributing

Want to improve this package? Feel free to fork and submit a pull request.

  1. Clone the repository:
    git clone https://github.com/Th85534/npm-packages.git
  2. Make changes and push to a new branch.
  3. Submit a Pull Request!

šŸ“œ License

This package is licensed under the MIT License.


šŸš€ Enjoy using Time Converter? Give it a ⭐ on GitHub!

1.0.2

5 months ago

1.0.1

5 months ago

1.0.0

5 months ago