Relative Date Tag

JavaScript Web Component
HTML / JS
GitHub Gist

What It Is

A tag which displays the relative timespan from right now to a specified date.

Status

Last Reviewed:

It’s used right now all over this site (including the “Last Reviewed” subheader above.)

Details

A web component that takes a date as an attribute, and will render a string representing a relative timespan from that date to the current moment.

<relative-date datetime="2024-08-13"></relative-date>

On load, the tag will calculate the difference between the value in the datetime attribute and the current date/time, then display it narratively (“2 weeks ago,” or whatever)

Here is the relative date between now and the day I was born (this is an actual usage of the tag; view source if you like):

You can add a suffix attribute, if you like:

I took the actual date logic from somewhere else, and I limited it to a minimum interval of one day (anything less than 24 hours is “Today”). If you wanted to go down to the hour or minute level, you’d need to change the code.