Skip to content

parseDuration

Parses a compact duration string (as produced by formatDuration, e.g. "1h 23m 45s") back into milliseconds.

Accepts any combination/order of h/m/s segments, with or without spaces between them ("1h30m" and "1h 30m" both work). A single leading - negates the whole duration, matching formatDuration’s output. Returns null when no valid segment is found.

Available since v3.0.0

import { parseDuration } from '@helpers4/date';
// or, from the all-in-one package (same code, one install):
import { parseDuration } from 'helpers4/date';
parseDuration(str: string): number | null
ParameterTypeDescription
strstringThe duration string to parse

number | null — The duration in milliseconds, or null if unparseable

Parse a compact duration string into milliseconds

Section titled “Parse a compact duration string into milliseconds”

The inverse of formatDuration() — accepts the same “1h 23m 45s” style output.

parseDuration('1h 23m 45s')
// => 5025000

Lets you branch on parse failure instead of silently getting 0 or NaN.

parseDuration('not a duration')
// => null

View source on GitHub