• Stars
    star
    1,506
  • Rank 30,088 (Top 0.7 %)
  • Language
    JavaScript
  • License
    The Unlicense
  • Created almost 11 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

361000 becomes "6 minutes, 1 second"

Humanize Duration

npm version

I have the time in milliseconds and I want it to become "30 minutes" or "3 days, 1 hour". Enter Humanize Duration!

This library is actively maintained but no new features will be added.

Installation

This package is available as humanize-duration on npm and Bower. You can also include the JavaScript file in the browser.

npm install humanize-duration

Basic usage

With require (like in Node or with common build systems):

const humanizeDuration = require("humanize-duration");
humanizeDuration(12000); // '12 seconds'

With a <script> tag:

<script src="humanize-duration.js"></script>
<script>
  humanizeDuration(12000);
</script>

Usage

By default, Humanize Duration will humanize down to the second, and will return a decimal for the smallest unit. It will humanize in English by default.

humanizeDuration(3000); // '3 seconds'
humanizeDuration(2250); // '2.25 seconds'
humanizeDuration(97320000); // '1 day, 3 hours, 2 minutes'

Options

You can change the settings by passing options as the second argument:

language

Language for unit display (accepts an ISO 639-1 code from one of the supported languages).

humanizeDuration(3000, { language: "es" }); // '3 segundos'
humanizeDuration(5000, { language: "ko" }); // '5 ì´ˆ'

fallbacks

Fallback languages if the provided language cannot be found (accepts an ISO 639-1 code from one of the supported languages). It works from left to right.

humanizeDuration(3000, { language: "bad language", fallbacks: ["en"] }); // '3 seconds'
humanizeDuration(3000, {
  language: "bad language",
  fallbacks: ["bad language", "es"],
}); // '3 segundos'

delimiter

String to display between the previous unit and the next value.

humanizeDuration(22140000, { delimiter: " and " }); // '6 hours and 9 minutes'
humanizeDuration(22140000, { delimiter: "--" }); // '6 hours--9 minutes'

spacer

String to display between each value and unit.

humanizeDuration(260040000, { spacer: " whole " }); // '3 whole days, 14 whole minutes'
humanizeDuration(260040000, { spacer: "" }); // '3days, 14minutes'

largest

Number representing the maximum number of units to display for the duration.

humanizeDuration(1000000000000); // '31 years, 8 months, 1 week, 19 hours, 46 minutes, 40 seconds'
humanizeDuration(1000000000000, { largest: 2 }); // '31 years, 8 months'

units

Array of strings to define which units are used to display the duration (if needed). Can be one, or a combination of any, of the following: ['y', 'mo', 'w', 'd', 'h', 'm', 's', 'ms']

humanizeDuration(3600000, { units: ["h"] }); // '1 hour'
humanizeDuration(3600000, { units: ["m"] }); // '60 minutes'
humanizeDuration(3600000, { units: ["d", "h"] }); // '1 hour'

round

Boolean value. Use true to round the smallest unit displayed (can be combined with largest and units).

humanizeDuration(1200); // '1.2 seconds'
humanizeDuration(1200, { round: true }); // '1 second'
humanizeDuration(1600, { round: true }); // '2 seconds'

decimal

String to substitute for the decimal point in a decimal fraction.

humanizeDuration(1200); // '1.2 seconds'
humanizeDuration(1200, { decimal: " point " }); // '1 point 2 seconds'

conjunction

String to include before the final unit. You can also set serialComma to false to eliminate the final comma.

humanizeDuration(22140000, { conjunction: " and " }); // '6 hours and 9 minutes'
humanizeDuration(22141000, { conjunction: " and " }); // '6 hours, 9 minutes, and 1 second'
humanizeDuration(22140000, { conjunction: " and ", serialComma: false }); // '6 hours and 9 minutes'
humanizeDuration(22141000, { conjunction: " and ", serialComma: false }); // '6 hours, 9 minutes and 1 second'

maxDecimalPoints

Number that defines a maximal decimal points for float values.

humanizeDuration(8123.456789); // 8.12 seconds
humanizeDuration(8123.456789, { maxDecimalPoints: 3 }); // 8.123 seconds
humanizeDuration(8123.456789, { maxDecimalPoints: 6 }); // 8.123456 seconds
humanizeDuration(8123.45, { maxDecimalPoints: 6 }); // 8.12345 seconds
humanizeDuration(8000, { maxDecimalPoints: 6 }); // 8 seconds

unitMeasures

Customize the value used to calculate each unit of time.

humanizeDuration(400); // '0.4 seconds'
humanizeDuration(400, {
  unitMeasures: {
    y: 365,
    mo: 30,
    w: 7,
    d: 1,
  },
}); // '1 year, 1 month, 5 days'

Combined example

humanizeDuration(3602000, {
  language: "es",
  round: true,
  spacer: " glorioso ",
  units: ["m"],
}); // '60 glorioso minutos'

Humanizers

If you find yourself setting same options over and over again, you can create a humanizer that changes the defaults, which you can still override later.

const spanishHumanizer = humanizeDuration.humanizer({
  language: "es",
  units: ["y", "mo", "d"],
});

spanishHumanizer(71177400000); // '2 años, 3 meses, 2 días'
spanishHumanizer(71177400000, { units: ["d", "h"] }); // '823 días, 19.5 horas'

You can also add new languages to humanizers. For example:

const shortEnglishHumanizer = humanizeDuration.humanizer({
  language: "shortEn",
  languages: {
    shortEn: {
      y: () => "y",
      mo: () => "mo",
      w: () => "w",
      d: () => "d",
      h: () => "h",
      m: () => "m",
      s: () => "s",
      ms: () => "ms",
    },
  },
});

shortEnglishHumanizer(15600000); // '4 h, 20 m'

You can also add languages after initializing:

const humanizer = humanizeDuration.humanizer()

humanizer.languages.shortEn = {
  y: () => 'y',
  // ...

Internally, the main humanizeDuration function is just a wrapper around a humanizer.

Supported languages

Humanize Duration supports the following languages:

Language Code
Afrikaans af
Albanian sq
Arabic ar
Basque eu
Bengali bn
Bulgarian bg
Catalan ca
Chinese, simplified zh_CN
Chinese, traditional zh_TW
Croatian hr
Czech cs
Danish da
Dutch nl
English en
Esperanto eo
Estonian et
Faroese fo
Farsi/Persian fa
Finnish fi
French fr
German de
Greek el
Hebrew he
Hindi hi
Hungarian hu
Icelandic is
Indonesian id
Italian it
Japanese ja
Kannada kn
Khmer km
Korean ko
Kurdish ku
Lao lo
Latvian lv
Lithuanian lt
Macedonian mk
Mongolian mn
Malay ms
Marathi mr
Norwegian no
Polish pl
Portuguese pt
Romanian ro
Russian ru
Serbian sr
Slovak sk
Slovenian sl
Spanish es
Swahili sw
Swedish sv
Tamil ta
Telugu te
Thai th
Turkish tr
Ukrainian uk
Urdu ur
Vietnamese vi
Welsh cy

For a list of supported languages, you can use the getSupportedLanguages function. The results may not be in the same order every time.

humanizeDuration.getSupportedLanguages();
// ['ar', 'bg', 'ca', 'cs', da', 'de', ...]

This function won't return any new languages you define; it will only return the defaults supported by the library.

Credits

Lovingly made by Evan Hahn with help from:

Licensed under the permissive Unlicense. Enjoy!

Related modules

More Repositories

1

Express.js-in-Action-code

Code from "Express.js in Action", a little book I wrote
JavaScript
166
star
2

ffmpeg-buddy

a lil webpage that helps you write ffmpeg commands
HTML
147
star
3

brainfuck-web-app

a web app written in Brainfuck that returns your user-agent to you
Brainfuck
138
star
4

English-text-highlighting

experiment: what if English text was highlighted
JavaScript
73
star
5

ScriptInclude

asynchronously load .js
JavaScript
45
star
6

dotfiles

Moved to https://gitlab.com/EvanHahn/dotfiles.
Shell
45
star
7

two-factor-auth-list

a list of websites supporting two-factor authentication
PHP
30
star
8

crystal-helmet

a port of the Node Helmet module to the Crystal programming language
Crystal
28
star
9

deep-proxy

obj.very.deeply.nested.property.isNow = 'possible'
JavaScript
15
star
10

haha.sh

a bash script that generates hearty laughter
Shell
15
star
11

tiny-coming-soon-page

a tiny "coming soon" page
HTML
14
star
12

Unity-RTS-camera

A little script for RTS games in Unity. Abandoned. Add an issue if you want to take over!
C#
14
star
13

airtable-cli

a command line interface to Airtable (WIP)
JavaScript
11
star
14

wren-please

Assertion library for Wren.
10
star
15

iscp

interactive scp
Shell
9
star
16

arraywrap.js

source moved to https://git.sr.ht/~evanhahn/arraywrap.js
JavaScript
6
star
17

check-ecmascript-version-compatibility

Test files for ES5 compatibility
JavaScript
6
star
18

functional-state-machine.js

a tiny javascript state machine that's just a function
JavaScript
6
star
19

SnackWrap

after changing a file, run a command. Abandoned. Add an issue if you want to take over!
Python
6
star
20

atom-language-brainfuck

Brainfuck syntax for Atom
6
star
21

evanhahn-dot-com

Repo now lives on Sourcehut
HTML
6
star
22

js13kgames-2013

my entry to js13kgames 2013
JavaScript
6
star
23

opt-out-list

Opt out of ad tracking on various websites
5
star
24

cyborg.txt

robots.txt utilities for Node
JavaScript
5
star
25

canvas-to-favicon

take a 16x16 canvas and send it to the favicon
JavaScript
5
star
26

node-persisted-json-object

make a normal object persist as JSON
JavaScript
4
star
27

MouseTracker.js

keep mouse.x and mouse.y updated
JavaScript
4
star
28

pomo

a command-line Pomodoro timer
Ruby
4
star
29

percentage.js

Project is now at https://git.sr.ht/~evanhahn/percentage.js
JavaScript
4
star
30

JSCPP

Port some JavaScript to C++.
C++
4
star
31

Gribbagrab

load them resources. Abandoned. Contact me if you want to take over!
JavaScript
4
star
32

Evan-Hahn-Project-Skeleton

PRETTY OUTDATED YEAH
C++
4
star
33

BRAINFUCK2000

A BRAINFUCK INTERPRETER FOR THE STARS
JavaScript
4
star
34

flood

my take on a Video Game
JavaScript
4
star
35

stackoverflow.com-q-30337525-804100

answering http://stackoverflow.com/q/30337525/804100
Ruby
4
star
36

braintree-hosted-fields-bootstrap

An unofficial jQuery plugin for Braintree's Hosted Fields and the Bootstrap framework.
HTML
4
star
37

code-doodles

doodles made of code
CoffeeScript
4
star
38

user-agent-bag

RFC-respecting User-Agent serialization and deserialization
JavaScript
3
star
39

setAttributes

call .setAttribute on a DOM node more easily
JavaScript
3
star
40

scrabbler

a python scrabble solver
Python
3
star
41

QRIt

Simple webpage that generates QR codes.
HTML
3
star
42

coinflip.js

randomly return true or false
JavaScript
3
star
43

image-to-table

a useless idea
JavaScript
3
star
44

trip-to-carbon-xyz

a light wrapper around triptocarbon.xyz
TypeScript
3
star
45

rename

interactive mv
Shell
2
star
46

ring-secure-headers

WIP: Ring (Clojure) security with HTTP headers.
Clojure
2
star
47

wren-querystring

querystring parser/stringifier for Wren
2
star
48

luluwrite

Pastebin + Medium. Abandoned. Add an issue if you want to take over!
Ruby
2
star
49

Recurry.js

abandoned. check out rrule.js
JavaScript
2
star
50

is-password-ok

is the password kinda ok
JavaScript
2
star
51

Content-Security-Policy-sandbox

a lil app for playing around with CSP
JavaScript
2
star
52

ring-tones

this name is a pun
CoffeeScript
2
star
53

hide-news-feed

hide the Facebook news feed in any browser. This project has been abandoned—please open an issue if you would like to take it over.
CSS
2
star
54

wren-vector3d

3D vectors for Wren
2
star
55

Fiesta.js

No longer maintained! See issues if you want to take over.
CoffeeScript
2
star
56

expecting.js

No longer maintained! See issues if you want to take over.
JavaScript
2
star
57

ticker

a lightweight wrapper on requestAnimationFrame
JavaScript
2
star
58

blooming-onion

a code doodle
CoffeeScript
2
star
59

lildash

NO LONGER MAINTAINED. Use 101.js.
JavaScript
2
star
60

airtable-clj

Clojure wrapper around the Airtable API (WIP)
Clojure
1
star
61

when-will-breath-of-the-wild-be-released

i want to know when the next Zelda comes out
JavaScript
1
star
62

Pingaling-for-Chrome

Monitor your network status from Chrome.
JavaScript
1
star
63

js1k-2016

fireworks!
HTML
1
star
64

mailtolink.js

make mailto: links
JavaScript
1
star
65

clone-github

clone all of a GitHub user's repositories
Ruby
1
star
66

toki-pona-to-hex

for fun
JavaScript
1
star
67

umpm

abandoned package manager for University of Michigan students. Add an issue if you want to take over the project!
Shell
1
star
68

startInterval

setInterval that starts immediately. made for a tutorial
JavaScript
1
star
69

who-are-you-on-facebook

proof of concept (WIP)
JavaScript
1
star
70

gopher-node-menudle

generate Gopher menus with Node. Abandoned. Add an issue if you want to take over!
JavaScript
1
star
71

Aubrey

turn any key-value store into a powerful collection (WIP)
JavaScript
1
star
72

MiniClass

tiny JavaScript classes. Abandoned. Add an issue if you want to take over!
JavaScript
1
star
73

JSTypes

Small JavaScript library that deals with variable types. Abandoned. Add an issue if you want to take over!
JavaScript
1
star
74

Circles-1K

Pretty circles in 1 kilobyte of JavaScript.
JavaScript
1
star
75

el-rando

command line tool to generate random stuff
Python
1
star
76

js1k-2015

pietime. won 10th place somehow
JavaScript
1
star
77

us-military-dj-names

us military operations make great DJ names
JavaScript
1
star
78

ExtJS-vs.-Sencha-Touch

Comparing the similar APIs of Sencha Touch and ExtJS.
JavaScript
1
star
79

patterns

make simple patterns that could be on a hipster shirt
JavaScript
1
star
80

Chucklehuck

Playing around with ChucK. Don't mind me.
1
star
81

truth-table

generate truth tables from the command line. made for a class
CoffeeScript
1
star
82

miniexpress

Express.js in under 50 lines. not for real use
JavaScript
1
star
83

nimi-mute

A Toki Pona dictionary.
JavaScript
1
star
84

xml-to-text

in goes the XML, out comes the plain text
Python
1
star
85

node-html-pack

inline styles and scripts and minify everything
JavaScript
1
star
86

oneatatime

don't execute an async function again until it's done (WIP)
JavaScript
1
star
87

js1k-2014

"dragon scales", my entry to js1k 2014
JavaScript
1
star
88

time-in-korea

a simple Android app that tells you the time in South Korea. Abandoned. Add an issue if you want to take over!
CSS
1
star
89

import-pinboard-to-standard-notes

a little web app to import Pinboard bookmarks into Standard Notes
JavaScript
1
star