Reference
API & Features
Creating, formatting, and parsing durations.
Features
Creating Duration
When creating a new Duration, you can specify time values in different units.
All fields are optional:
days: Number of dayshours: Number of hoursminutes: Number of minutesseconds: Number of secondsmilliseconds: Number of milliseconds
const duration = new Duration({ hours: 1.5, minutes: 10, seconds: 120 }); // 1h 42 mins
// or
const duration = Duration.from(6120, 'sec'); // 1h 42 mins
// or
const duration = Duration.fromDate(Date.now()); // 0msFormatting Duration
You can use the format() method to customize how the duration is displayed.
The method accepts a pattern string with the following placeholders:
%d: Number of days%h: Number of hours%m: Number of minutes%s: Number of seconds%l: Number of milliseconds
Or use one of the predefined formats:
'short': Compact format (e.g. '1h 30m')'medium': Medium format (e.g. '1 hr 30 mins')'long': Full format (e.g. '1 hour 30 minutes')
For example:
> const duration = Duration.from(5_400_000)
> duration.format('%h hr %m min ago')
'1 hr 30 min ago'Parsing Duration
You can also create Duration objects by parsing English duration strings using the parse() method.
It supports various formats:
- Short format:
'1d 2h 3m 4s 5ms' - Medium format:
'1 day 2 hrs 3 mins 4 secs 5 ms' - Long format:
'1 day 2 hours 3 minutes 4 seconds 5 milliseconds' - Mixed formats:
'1 day 2h 30 minutes' - Single units:
'30 seconds','1 hour' - Decimal values:
'1.5 hours','2.5 days' - Plain numbers:
'1000'(defaults to milliseconds)
This makes it perfect for round-trip conversion:
> const original = new Duration({ hours: 2, minutes: 30 });
> const parsed = Duration.parse(original.medium);
> parsed.inMinutes === original.inMinutes;
trueNote that this utility does not currently support locales. All output formats are in English only. If you need localized duration strings, you'll need to implement that separately in your application (check out the
feature/localesbranch).