@divante-adventure/duration

0.1.2 • Public • Published

Usage

Samples

let Duration = require('duration');

new Duration('15h').timestamp(); // 15 * 60 * 60 = 54000 seconds
new Duration('15h').hours(); // 15
new Duration('15h').minutes(); // 0
new Duration('15h').seconds(); // 0

new Duration('7.5h').timestamp(); // 7.5 * 60 * 60 = 27000 seconds
new Duration('7.5h').hours(); // 7
new Duration('7.5h').minutes(); // 30
new Duration('7.5h').seconds(); // 0

new Duration('3 h 20m 5s').timestamp(); // 12005 seconds
new Duration('3 h 20m 5s').hours(); // 3
new Duration('3 h 20m 5s').minutes(); // 20
new Duration('3 h 20m 5s').seconds(); // 5

Validating

new Duration('3h').isValid(); // true
new Duration('h3').isValid(); // false

White characters are ignored

let a = new Duration('3h 20.5m 5s');
let b = new Duration('3 h 20.5 m 5 s');
let c = new Duration('3h20.5m5s');
let d = new Duration('3 h 2 0 . 5 m 5 s');

a.timestamp() === b.timestamp() === c.timestamp() === d.timestamp(); //true

Accepting timestamps

new Duration(0); // 0 seconds
new Duration(60); // 1 minute
new Duration(-5).isValid(); // false

Formatting

new Duration(0).format('{H}h {MM}m {SS}s'); // "0h 00m 00s"
new Duration(60).format('{M} minute(s)'); // "1 minute(s)"

Accepted values in formats:

  • {H} / {HH} - hours (second value with padding to 2 digits)
  • {M} / {MM} - minutes
  • {S} / {SS} - seconds

You can also pass object as a format to use conditional formatting. If you won't pass anything, following default object will be used:

let defaultConditionalFormat = {
  zero: '',
  h: '{H}h',
  m: '{M}m',
  s: '{S}s',
  hm: '{H}h {MM}m',
  hs: '{H}h {M}m {SS}s',
  ms: '{M}m {SS}s',
  hms: '{H}h {MM}m {SS}s'
};

Where for example hm format will be used when hours and minutes > 0 and seconds are equal to zero. If you pass an object, undefined formats will be replaced with default ones.

Readme

Keywords

none

Package Sidebar

Install

npm i @divante-adventure/duration

Weekly Downloads

1

Version

0.1.2

License

UNLICENSED

Unpacked Size

11.2 kB

Total Files

9

Last publish

Collaborators

  • divante