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
- Type
90 minutesto see it format in words, total1.5hours, and serialize toPT90M. - Try
2 weeks and 3 daysorPT45Mto mix natural phrases with ISO 8601 strings. - Type
soonto 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.