typescript 29 lines · 7 steps

Parsing ISO 8601 durations to seconds

A single regex plus a units-to-seconds table turns strings like PT1H30M into a numeric total.

Explained by highlit
1const ISO_DURATION = /^P(?:(\d+(?:\.\d+)?)Y)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)W)?(?:(\d+(?:\.\d+)?)D)?(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?$/;
2 
3const SECONDS_PER = {
4 years: 365 * 24 * 60 * 60,
5 months: 30 * 24 * 60 * 60,
6 weeks: 7 * 24 * 60 * 60,
7 days: 24 * 60 * 60,
8 hours: 60 * 60,
9 minutes: 60,
10 seconds: 1,
11} as const;
12 
13export function parseIsoDuration(input: string): number {
14 const match = ISO_DURATION.exec(input.trim());
15 if (!match || match[0] === "P" || match[0] === "PT") {
16 throw new RangeError(`Invalid ISO 8601 duration: ${input}`);
17 }
18 
19 const [, years, months, weeks, days, hours, minutes, seconds] = match;
20 const parts = { years, months, weeks, days, hours, minutes, seconds };
21 
22 let total = 0;
23 for (const [unit, raw] of Object.entries(parts)) {
24 if (raw === undefined) continue;
25 total += parseFloat(raw) * SECONDS_PER[unit as keyof typeof SECONDS_PER];
26 }
27 
28 return total;
29}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A well-structured regex with capture groups can both validate and extract fields in one pass.
  2. 2Pairing named units with a conversion table keeps the accumulation loop tiny and data-driven.
  3. 3Guarding against the empty P/PT matches closes a gap the regex alone would let through.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing ISO 8601 durations to seconds — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code