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 { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import { Reflector } from '@nestjs/core'; import { JwtService } from '@nestjs/jwt';
How a GraphQL auth guard works in NestJS
authentication
authorization
jwt
Intermediate
7 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.