1.0.4 • Published 5 years ago

@marchsabino/duration v1.0.4

Weekly downloads
5
License
MIT
Repository
github
Last release
5 years ago

Duration

Easily create and format durations.

Installation

npm i @marchsabino/duration

or

yarn add @marchsabino/duration

Basic Usage

import duration from "@marchsabino/duration";

// Print so that a human can read
duration(10).humanize(); // "10 seconds"
duration(10, "seconds").humanize(); // "10 seconds"
duration(121, "seconds").humanize(); // "2 minutes 1 second"
duration(2.5, "minutes").humanize(); // "2 minutes 30 seconds"
duration(1, "hours").humanize(); // 1 hour
duration(1.5, "days").humanize(); // 1 day 12 hours 0 minutes 0 seconds

// Print in a format of your choosing
console.log(duration(182).format("%m [minutes]")); // "3 minutes"
console.log(duration(67).format("%mm [minutes] and %ss [seconds]")); // "1 minute and 7 seconds"
console.log(duration(123).format("%hh:%mm:%ss")); // "00:02:03"

API

duration(duration: number, interval?: string): Duration

Creates a new duration

Where duration is any number and interval is an optional string of any of the following values:

  • day or days
  • hour or hours
  • minute or minutes
  • second or seconds
  • millisecond or milliseconds

Note: if interval is not specified, it will default to seconds

Duration#format(format?: string)

Formats the duration to your specification

Formatting values:

  • %d - formats days "as is" e.g. 123
  • %hh - formats hours with leading 0's e.g. 08
  • %h - formats hours "as is" e.g. 8
  • %mm - formats minutes with leading 0's e.g. 01
  • %m - formats minutes "as is" e.g. 4 or 23
  • %ss - formats seconds with leading 0's e.g. 03
  • %s - formats seconds "as is" e.g. 59
  • %SSS - formats milliseconds with leading 0's e.g. 009
  • %SS - formats milliseconds with leading 0's e.g. 01
  • %S - formats milliseconds "as is" e.g. 1, 50, or 999
  • [days] - displays either "days" or "day" depending on days
  • [hours] - displays either "hours" or "hour" depending on hours
  • [minutes] - displays either "minutes" or "minute" depending on minutes
  • [seconds] - displays either "seconds" or "second" depending on seconds

Sample Usage

import duration from "@marchsabino/duration";

console.log(duration(182).format("%m [minutes]")); // "3 minutes"
console.log(duration(67).format("%mm [minutes] and %ss [seconds]")); // "1 minute and 7 seconds"
console.log(duration(123).format("%hh:%mm:%ss")); // "00:02:03"

Duration#humanize()

Formats the duration into an easily human-readable format.