Humanize Duration converts millisecond durations into human-readable strings in over 100 languages. It provides flexible formatting options including custom delimiters, rounding, unit selection, decimal precision control, and comprehensive localization support for internationalized applications.
npm install humanize-durationconst humanizeDuration = require("humanize-duration");For ES modules:
import humanizeDuration from "humanize-duration";For TypeScript:
import humanizeDuration from "humanize-duration";
// Types are available through JSDoc annotationsIn the browser with a script tag:
<script src="humanize-duration.js"></script>
<!-- humanizeDuration is now available globally -->const humanizeDuration = require("humanize-duration");
// Basic usage
humanizeDuration(12000);
// => "12 seconds"
humanizeDuration(2250);
// => "2.25 seconds"
humanizeDuration(97320000);
// => "1 day, 3 hours, 2 minutes"
// With options
humanizeDuration(12000, { language: 'es' });
// => "12 segundos"
humanizeDuration(12000, { units: ['h', 'm', 's'] });
// => "12 seconds"Humanize Duration is built around several key components:
Converts millisecond durations to human-readable strings with extensive customization options.
/**
* Convert millisecond durations to human-readable strings
* @param ms - Duration in milliseconds (always converted to positive number)
* @param options - Optional formatting configuration
* @returns Human-readable duration string
*/
function humanizeDuration(ms: number, options?: Options): string;
/**
* Additional methods available on the main function
*/
declare namespace humanizeDuration {
const humanizer: typeof humanizer;
const getSupportedLanguages: typeof getSupportedLanguages;
}Creates customized humanizer instances with preset configuration options.
/**
* Create a humanizer instance with preset options
* @param passedOptions - Default options for this humanizer
* @returns Configured humanizer function with preset defaults
*/
function humanizer(passedOptions?: Options): (ms: number, humanizerOptions?: Options) => string;Usage Example:
const humanizer = humanizeDuration.humanizer({
language: 'fr',
units: ['h', 'm'],
round: true
});
humanizer(7200000); // "2 heures"
humanizer(7320000); // "2 heures, 2 minutes"Provides access to all supported language codes for internationalization.
/**
* Get array of all supported language codes
* @returns Array of language codes (e.g., ['af', 'am', 'ar', ...])
*/
function getSupportedLanguages(): string[];Usage Example:
const languages = humanizeDuration.getSupportedLanguages();
console.log(languages); // ['af', 'am', 'ar', 'bg', 'bn', ...]interface Options {
/** Language code for localization (default: "en") */
language?: string;
/** Custom language definitions to supplement built-in languages */
languages?: Record<string, Language>;
/** Fallback languages if primary language not found */
fallbacks?: string[];
/** Separator between time units (default: ", " for most languages, language-specific for others) */
delimiter?: string;
/** Space between number and unit name (default: " ") */
spacer?: string;
/** Round to avoid decimals (default: false) */
round?: boolean;
/** Maximum number of time units to display (default: unlimited) */
largest?: number;
/** Which time units to include (default: ["y", "mo", "w", "d", "h", "m", "s"]) */
/** Note: "ms" is not included in the default units array */
units?: UnitName[];
/** Decimal point character (default: ".") */
decimal?: string;
/** Word to join the last two elements (e.g., "and") */
conjunction?: string;
/** Maximum decimal places to show */
maxDecimalPoints?: number;
/** Custom millisecond values for each unit */
unitMeasures?: UnitMeasures;
/** Use Oxford comma with conjunction (default: true) */
serialComma?: boolean;
/** Replace digits 0-9 with custom characters */
digitReplacements?: DigitReplacements;
}Configuration Examples:
// Language localization
humanizeDuration(3000, { language: 'de' }); // "3 Sekunden"
// Custom delimiter and conjunction
humanizeDuration(97320000, {
delimiter: ' | ',
conjunction: ' and '
}); // "1 day | 3 hours and 2 minutes"
// Limit units and enable rounding
humanizeDuration(97320000, {
largest: 2,
round: true
}); // "1 day, 3 hours"
// Custom spacer and decimal
humanizeDuration(2250, {
spacer: '_',
decimal: ','
}); // "2,25_seconds"type UnitName = "y" | "mo" | "w" | "d" | "h" | "m" | "s" | "ms";
interface UnitMeasures {
/** Year in milliseconds */
y: number;
/** Month in milliseconds */
mo: number;
/** Week in milliseconds */
w: number;
/** Day in milliseconds */
d: number;
/** Hour in milliseconds */
h: number;
/** Minute in milliseconds */
m: number;
/** Second in milliseconds */
s: number;
/** Millisecond */
ms: number;
}Default Unit Values:
{
y: 31557600000, // ~365.25 days
mo: 2629800000, // ~30.44 days
w: 604800000, // 7 days
d: 86400000, // 24 hours
h: 3600000, // 60 minutes
m: 60000, // 60 seconds
s: 1000, // 1000 milliseconds
ms: 1 // 1 millisecond
}interface Language {
/** Year unit name(s) - string or function for pluralization */
y: Unit;
/** Month unit name(s) */
mo: Unit;
/** Week unit name(s) */
w: Unit;
/** Day unit name(s) */
d: Unit;
/** Hour unit name(s) */
h: Unit;
/** Minute unit name(s) */
m: Unit;
/** Second unit name(s) */
s: Unit;
/** Millisecond unit name(s) */
ms: Unit;
/** Decimal character for this language (optional) */
decimal?: string;
/** Delimiter for this language (optional) */
delimiter?: string;
/** Custom digit replacements (optional) */
_digitReplacements?: DigitReplacements;
/** Whether to put number before unit (optional) */
_numberFirst?: boolean;
/** Hide count when value is 2 (optional) */
_hideCountIf2?: boolean;
}
type Unit = string | ((unitCount: number) => string);
type DigitReplacements = [string, string, string, string, string, string, string, string, string, string];Custom Language Example:
const customHumanizer = humanizeDuration.humanizer({
language: 'shortEn',
languages: {
shortEn: {
y: 'yr',
mo: 'mo',
w: 'wk',
d: 'day',
h: 'hr',
m: 'min',
s: 'sec',
ms: 'ms'
}
}
});
customHumanizer(97320000); // "1 day, 3 hr, 2 min"The library includes built-in support for 100+ languages including: af (Afrikaans), am (Amharic), ar (Arabic), bg (Bulgarian), bn (Bengali), ca (Catalan), ckb (Central Kurdish), cs (Czech), cy (Welsh), da (Danish), de (German), el (Greek), en (English), eo (Esperanto), es (Spanish), et (Estonian), eu (Basque), fa (Persian), fi (Finnish), fo (Faroese), fr (French), he (Hebrew), hi (Hindi), hr (Croatian), hu (Hungarian), id (Indonesian), is (Icelandic), it (Italian), ja (Japanese), km (Khmer), kn (Kannada), ko (Korean), ku (Kurdish), lo (Lao), lt (Lithuanian), lv (Latvian), mk (Macedonian), mn (Mongolian), mr (Marathi), ms (Malay), nl (Dutch), no (Norwegian), pl (Polish), pt (Portuguese), ro (Romanian), ru (Russian), sk (Slovak), sl (Slovenian), sq (Albanian), sr (Serbian), sr_Latn (Serbian Latin), sv (Swedish), sw (Swahili), ta (Tamil), te (Telugu), th (Thai), tr (Turkish), uk (Ukrainian), ur (Urdu), uz (Uzbek), uz_CYR (Uzbek Cyrillic), vi (Vietnamese), zh_CN (Chinese Simplified), zh_TW (Chinese Traditional).
The library handles errors in the following ways:
Math.abs()Error Handling Example:
try {
humanizeDuration(12000, {
language: 'nonexistent',
fallbacks: ['en']
});
} catch (error) {
console.log(error.message); // Uses fallback language
}
// Invalid input handling
humanizeDuration("12000"); // "12 seconds" (string converted to number)
humanizeDuration(-5000); // "5 seconds" (made positive)