native-dates

Examples / Durations

Typed durations

Parse human duration phrases and ISO 8601 strings from a text input into words, total hours, and wire format.

Try this

  1. Type 90 minutes to see it format in words, total 1.5 hours, and serialize to PT90M.
  2. Try 2 weeks and 3 days or PT45M to mix natural phrases with ISO 8601 strings.
  3. Type soon to see the error message explain what went wrong and suggest valid examples.
import { duration } from 'native-dates';

const input = document.querySelector('input');
const output = document.querySelector('#output');

function render() {
  try {
    const length = duration(input.value);
    output.innerHTML = `
      <dt>In words</dt><dd>${length.format()}</dd>
      <dt>In hours</dt><dd>${length.total('hours')}</dd>
      <dt>ISO 8601</dt><dd><code>${length}</code></dd>`;
  }
  catch (error) {
    output.innerHTML = `<dt>Refused</dt><dd class="refused">${error.message}</dd>`;
  }
}

input.addEventListener('input', render);
render();

Starting…

How it works

Passing user text to duration() reads everyday unit phrases and ISO 8601 strings into one structured value.

From there, format() spells the length out in words and total('hours') converts the span into a single decimal number. String interpolation outputs the standard ISO 8601 form for a database or API payload.

Unreadable input throws an error whose error.message identifies the invalid input and shows valid examples right in the page.