or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# Humanize Duration

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: humanize-duration

7

- **Package Type**: npm

8

- **Language**: JavaScript (with TypeScript support via JSDoc)

9

- **Installation**: `npm install humanize-duration`

10

- **Version**: 3.33.0

11

12

## Core Imports

13

14

```javascript

15

const humanizeDuration = require("humanize-duration");

16

```

17

18

For ES modules:

19

20

```javascript

21

import humanizeDuration from "humanize-duration";

22

```

23

24

For TypeScript:

25

26

```typescript

27

import humanizeDuration from "humanize-duration";

28

// Types are available through JSDoc annotations

29

```

30

31

In the browser with a script tag:

32

33

```html

34

<script src="humanize-duration.js"></script>

35

<!-- humanizeDuration is now available globally -->

36

```

37

38

## Basic Usage

39

40

```javascript

41

const humanizeDuration = require("humanize-duration");

42

43

// Basic usage

44

humanizeDuration(12000);

45

// => "12 seconds"

46

47

humanizeDuration(2250);

48

// => "2.25 seconds"

49

50

humanizeDuration(97320000);

51

// => "1 day, 3 hours, 2 minutes"

52

53

// With options

54

humanizeDuration(12000, { language: 'es' });

55

// => "12 segundos"

56

57

humanizeDuration(12000, { units: ['h', 'm', 's'] });

58

// => "12 seconds"

59

```

60

61

## Architecture

62

63

Humanize Duration is built around several key components:

64

65

- **Main Function**: Direct duration formatting with optional configuration

66

- **Humanizer Factory**: Creates customized instances with preset options

67

- **Language System**: Built-in definitions for 100+ languages with fallback support

68

- **Unit System**: Configurable time units (years, months, weeks, days, hours, minutes, seconds, milliseconds)

69

- **Formatting Engine**: Handles pluralization, decimal formatting, and cultural number display

70

71

## Capabilities

72

73

### Duration Formatting

74

75

Converts millisecond durations to human-readable strings with extensive customization options.

76

77

```javascript { .api }

78

/**

79

* Convert millisecond durations to human-readable strings

80

* @param ms - Duration in milliseconds (always converted to positive number)

81

* @param options - Optional formatting configuration

82

* @returns Human-readable duration string

83

*/

84

function humanizeDuration(ms: number, options?: Options): string;

85

86

/**

87

* Additional methods available on the main function

88

*/

89

declare namespace humanizeDuration {

90

const humanizer: typeof humanizer;

91

const getSupportedLanguages: typeof getSupportedLanguages;

92

}

93

```

94

95

### Humanizer Factory

96

97

Creates customized humanizer instances with preset configuration options.

98

99

```javascript { .api }

100

/**

101

* Create a humanizer instance with preset options

102

* @param passedOptions - Default options for this humanizer

103

* @returns Configured humanizer function with preset defaults

104

*/

105

function humanizer(passedOptions?: Options): (ms: number, humanizerOptions?: Options) => string;

106

```

107

108

**Usage Example:**

109

110

```javascript

111

const humanizer = humanizeDuration.humanizer({

112

language: 'fr',

113

units: ['h', 'm'],

114

round: true

115

});

116

117

humanizer(7200000); // "2 heures"

118

humanizer(7320000); // "2 heures, 2 minutes"

119

```

120

121

### Language Support

122

123

Provides access to all supported language codes for internationalization.

124

125

```javascript { .api }

126

/**

127

* Get array of all supported language codes

128

* @returns Array of language codes (e.g., ['af', 'am', 'ar', ...])

129

*/

130

function getSupportedLanguages(): string[];

131

```

132

133

**Usage Example:**

134

135

```javascript

136

const languages = humanizeDuration.getSupportedLanguages();

137

console.log(languages); // ['af', 'am', 'ar', 'bg', 'bn', ...]

138

```

139

140

## Configuration Options

141

142

```javascript { .api }

143

interface Options {

144

/** Language code for localization (default: "en") */

145

language?: string;

146

147

/** Custom language definitions to supplement built-in languages */

148

languages?: Record<string, Language>;

149

150

/** Fallback languages if primary language not found */

151

fallbacks?: string[];

152

153

/** Separator between time units (default: ", " for most languages, language-specific for others) */

154

delimiter?: string;

155

156

/** Space between number and unit name (default: " ") */

157

spacer?: string;

158

159

/** Round to avoid decimals (default: false) */

160

round?: boolean;

161

162

/** Maximum number of time units to display (default: unlimited) */

163

largest?: number;

164

165

/** Which time units to include (default: ["y", "mo", "w", "d", "h", "m", "s"]) */

166

/** Note: "ms" is not included in the default units array */

167

units?: UnitName[];

168

169

/** Decimal point character (default: ".") */

170

decimal?: string;

171

172

/** Word to join the last two elements (e.g., "and") */

173

conjunction?: string;

174

175

/** Maximum decimal places to show */

176

maxDecimalPoints?: number;

177

178

/** Custom millisecond values for each unit */

179

unitMeasures?: UnitMeasures;

180

181

/** Use Oxford comma with conjunction (default: true) */

182

serialComma?: boolean;

183

184

/** Replace digits 0-9 with custom characters */

185

digitReplacements?: DigitReplacements;

186

}

187

```

188

189

**Configuration Examples:**

190

191

```javascript

192

// Language localization

193

humanizeDuration(3000, { language: 'de' }); // "3 Sekunden"

194

195

// Custom delimiter and conjunction

196

humanizeDuration(97320000, {

197

delimiter: ' | ',

198

conjunction: ' and '

199

}); // "1 day | 3 hours and 2 minutes"

200

201

// Limit units and enable rounding

202

humanizeDuration(97320000, {

203

largest: 2,

204

round: true

205

}); // "1 day, 3 hours"

206

207

// Custom spacer and decimal

208

humanizeDuration(2250, {

209

spacer: '_',

210

decimal: ','

211

}); // "2,25_seconds"

212

```

213

214

## Time Units

215

216

```javascript { .api }

217

type UnitName = "y" | "mo" | "w" | "d" | "h" | "m" | "s" | "ms";

218

219

interface UnitMeasures {

220

/** Year in milliseconds */

221

y: number;

222

/** Month in milliseconds */

223

mo: number;

224

/** Week in milliseconds */

225

w: number;

226

/** Day in milliseconds */

227

d: number;

228

/** Hour in milliseconds */

229

h: number;

230

/** Minute in milliseconds */

231

m: number;

232

/** Second in milliseconds */

233

s: number;

234

/** Millisecond */

235

ms: number;

236

}

237

```

238

239

**Default Unit Values:**

240

241

```javascript

242

{

243

y: 31557600000, // ~365.25 days

244

mo: 2629800000, // ~30.44 days

245

w: 604800000, // 7 days

246

d: 86400000, // 24 hours

247

h: 3600000, // 60 minutes

248

m: 60000, // 60 seconds

249

s: 1000, // 1000 milliseconds

250

ms: 1 // 1 millisecond

251

}

252

```

253

254

## Language Definitions

255

256

```javascript { .api }

257

interface Language {

258

/** Year unit name(s) - string or function for pluralization */

259

y: Unit;

260

/** Month unit name(s) */

261

mo: Unit;

262

/** Week unit name(s) */

263

w: Unit;

264

/** Day unit name(s) */

265

d: Unit;

266

/** Hour unit name(s) */

267

h: Unit;

268

/** Minute unit name(s) */

269

m: Unit;

270

/** Second unit name(s) */

271

s: Unit;

272

/** Millisecond unit name(s) */

273

ms: Unit;

274

/** Decimal character for this language (optional) */

275

decimal?: string;

276

/** Delimiter for this language (optional) */

277

delimiter?: string;

278

/** Custom digit replacements (optional) */

279

_digitReplacements?: DigitReplacements;

280

/** Whether to put number before unit (optional) */

281

_numberFirst?: boolean;

282

/** Hide count when value is 2 (optional) */

283

_hideCountIf2?: boolean;

284

}

285

286

type Unit = string | ((unitCount: number) => string);

287

type DigitReplacements = [string, string, string, string, string, string, string, string, string, string];

288

```

289

290

**Custom Language Example:**

291

292

```javascript

293

const customHumanizer = humanizeDuration.humanizer({

294

language: 'shortEn',

295

languages: {

296

shortEn: {

297

y: 'yr',

298

mo: 'mo',

299

w: 'wk',

300

d: 'day',

301

h: 'hr',

302

m: 'min',

303

s: 'sec',

304

ms: 'ms'

305

}

306

}

307

});

308

309

customHumanizer(97320000); // "1 day, 3 hr, 2 min"

310

```

311

312

## Supported Languages

313

314

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).

315

316

## Error Handling

317

318

The library handles errors in the following ways:

319

320

- **Invalid Input**: Non-numeric inputs are converted to numbers using JavaScript coercion, then made positive with `Math.abs()`

321

- **Invalid Language**: Throws an error "No language found." if the specified language and all fallbacks are unavailable

322

- **Invalid Fallbacks**: Throws an error "fallbacks must be an array with at least one element" if fallbacks is provided but empty or not an array

323

324

**Error Handling Example:**

325

326

```javascript

327

try {

328

humanizeDuration(12000, {

329

language: 'nonexistent',

330

fallbacks: ['en']

331

});

332

} catch (error) {

333

console.log(error.message); // Uses fallback language

334

}

335

336

// Invalid input handling

337

humanizeDuration("12000"); // "12 seconds" (string converted to number)

338

humanizeDuration(-5000); // "5 seconds" (made positive)

339

```