Convert Time Strings To Seconds/Milliseconds – convert-time-string

Category: Date & Time , Javascript | October 12, 2023
Views Total:14 views
Official Page:Go to website
Last Update:October 12, 2023


Convert Time Strings To Seconds/Milliseconds – convert-time-string


convert-time-string is a tiny TypeScript/JavaScript library for quickly converting time strings into seconds or milliseconds.

How to use it:

1. Install the convert-time-string with NPM/Yarn.

# Yarn
$ yarn convert-time-string
$ npm i convert-time-string

2. Import the convert-time-string.

// ES module
import { convertTimeString, TimeUnitOutPut } from 'convert-time-string';
// CommonJS
const { convertTimeString, TimeUnitOutPut } = require('convert-time-string');

3. The main functionality of convert-time-string comes from the convertTimeString() function. It accepts a time string like “1d 2h 30m” and converts it to milliseconds or seconds, depending on the unit parameter. Hint: The time units supported are s(seconds), m(minutes), h(hours), d(days), M(months), and y(years). You can specify a single unit like “5h” or combine multiple units like “1d 15h”.

// => 95400000
const timeValue = convertTimeString('1d 2h 30m');
// => 95400
const timeValue = convertTimeString('1d 2h 30m', 'second');

4. By default, leap years are not considered when converting years. But you can enable support for leap years with the leapYear parameter:

// => 31622400
const timeValue = convertTimeString('1y', 'second', true);
// => 31536000
const timeValue = convertTimeString('1y', 'second');

You Might Be Interested In:

Leave a Reply