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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A well-structured regex with capture groups can both validate and extract fields in one pass.
- 2Pairing named units with a conversion table keeps the accumulation loop tiny and data-driven.
- 3Guarding against the empty P/PT matches closes a gap the regex alone would let through.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-iso-8601-durations-to-seconds-explained-typescript-3125/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.