A small and fast time utility which makes working with time, duration, date super easy. It contains a number of useful small utility methods to work with time and date.
Read Full Documentation here.
# npm
npm i @imranbarbhuiya/duration
# yarn
yarn add @imranbarbhuiya/duration
import { parse, format, prettyFormat, date, relativeTime, Formatter } from '@imranbarbhuiya/duration';
const { parse, format, prettyFormat, date, relativeTime, Formatter } = require('@imranbarbhuiya/duration');
// string => number
parse('1s 1min 1h 1d 1w 1mo 1y'); // 34844461001
parse('2 days'); //=> 172800000
parse('1d'); //=> 86400000
parse('-3 days'); //=> -259200000
// number => string
format(2 * 60000); //=> 2m
format(-3 * 60000, { long: true }); //=> -3 minutes
format(parse('10 hours'), { long: true }); //=> 10 hours
// number to string (multiple units)
prettyFormat(60000); //=> 1 minute
prettyFormat(121000); //=> 2 minutes, 1 second
prettyFormat(1000 * 60 * 60 * 60 * 24 * 30, { format: 'short' }); //=> 1mo
prettyFormat(86406010, {
format: 'short',
patterns: ['hour', 'minute', 'second', 'millisecond'],
separator: ' '
}); //=> 24h 6s 10ms
Writing these patterns every time is a pain. That's why there is a Formatter class which can be used to format multiple times without repeating yourself.
const formatter = new Formatter({
format: 'short',
patterns: ['hour', 'minute', 'second', 'millisecond'],
separator: ' '
});
formatter.format(1000 * 60 * 60 * 24 * 30); //=> 720h
formatter.format(86406010); //=> 24h 6s 10ms
// format a date
date('2022-01-01', 'YYYY-MMM-Do'); //=> 2022-Jan-Saturday
date('2022-01-01T00:00:00.000Z', 'yyyy-MM-D HH:mm:ss.SS Z'); //=> 2022-01-1 00:00:00.00 0
date('2022-01-01T00:00:00.000Z', 'yyyy-MMMM-DDD HH:mm:ss.SS'); //=> 2022-January-Sat 00:00:00.00
// format a date as relative date
relativeTime(Date.now() + 1000); //=> in a few seconds
relativeTime(Date.now() - 1000 * 60 * 60); //=> an hour ago
If you want to support me by donating, you can do so by using any of the following methods. Thank you very much in advance!
Thanks goes to these wonderful people (emoji key):
Parbez 💻 🚧 🤔 |
WhiteSource Renovate 🚧 |
This project follows the all-contributors specification. Contributions of any kind welcome!
Generated using TypeDoc