Duration
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.
Documentation
Read Full Documentation here.
Install
# npm
npm i @imranbarbhuiya/duration
# yarn
yarn add @imranbarbhuiya/duration
Usage
esm or Typescript
import { parse, format, prettyFormat, date, relativeTime, Formatter } from '@imranbarbhuiya/duration';
CommonJS
const { parse, format, prettyFormat, date, relativeTime, Formatter } = require('@imranbarbhuiya/duration');
parse
// string => number
parse('1s 1min 1h 1d 1w 1mo 1y'); // 34844461001
parse('2 days'); //=> 172800000
parse('1d'); //=> 86400000
parse('-3 days'); //=> -259200000
format
// number => string
format(2 * 60000); //=> 2m
format(-3 * 60000, { long: true }); //=> -3 minutes
format(parse('10 hours'), { long: true }); //=> 10 hours
prettyFormat
// 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.
Formatter
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
date
// 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
relativeTime
// format a date as relative date
relativeTime(Date.now() + 1000); //=> in a few seconds
relativeTime(Date.now() - 1000 * 60 * 60); //=> an hour ago
Buy me some doughnuts
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!
Contributors ✨
Thanks goes to these wonderful people (emoji key):
Parbez 💻 🚧 🤔 |
WhiteSource Renovate 🚧 |
This project follows the all-contributors specification. Contributions of any kind welcome!