Create a date duration pipe in Angular to generate ISO valid duration strings

The most current version as of .

The HTML <time>-element comes across with its datetime attribute. As a value we can provide a date, but also valid duration string according to ISO 8601.

Here is what the official specs say:

a valid duration string as defined in the [HTML5] specification

To format a normal date in Angular we can make use of the DatePipe.

<time [dateTime]="'2023-01-01' | date: 'full'"></time>

Note, that the pipe is assigend to th element with data binding and the attribute name is dateTime, not datetime.

As there is no Angular pipe to do something simular with durations, we have to write our own pipe.

For that we can use the functionality of moment.js.

First, install it from npm:

npm install --save moment

Next, generate the Pipe with Angular CLI:

ng g p date-duration

That gives uns a date-duration.pipe.ts. In that file we will write our pipe logic.

In the file, we first of all have to import moment:

import * as moment from "moment";

And here is the magical method for the pipe class:

/**
 * Transform two dates into a ISO duration string.
 * @param {string[]} values
 * @returns {string}
 */
transform(values: string[]): string {
    const start = moment(values[0])
    const end = moment(values[1])
    const duration = moment.duration(end.diff(start))
    return duration.toISOString()
}

After importing the pipe to our module, we can use the pipe in our module component templates to transform date string into a valid ISO duration string.

<time [dateTime]="['2022-01-01', '2023-01-01'] | dateDuration"></time>

The above example finally results in the following HTML:

<time datetime="PT8760H"></time>
— David Wolf