Relative Time Element for Time Ago Text

Category: Date & Time , Javascript , Recommended | June 17, 2026
Authorgithub
Last UpdateJune 17, 2026
LicenseMIT
Views0 views
Relative Time Element for Time Ago Text

Relative Time Element is a web component that formats ISO timestamps as localized dates, relative time text, or duration strings.

It helps you display readable time values such as “5 minutes ago,” “in 2 days,” or “on Apr 1, 2030” directly from HTML markup.

The library works as a browser-first web component and uses the native Intl.DateTimeFormat and Intl.RelativeTimeFormat APIs.

It’s ideal for static pages, server-rendered apps, cached HTML fragments, activity feeds, comment lists, dashboards, and documentation pages that need relative time display without a date formatting framework.

Features:

  • Format ISO timestamps as relative time text.
  • Display localized absolute dates.
  • Show countdown-style duration values.
  • Auto-update visible time text.
  • Respect browser locale preferences.
  • Support custom time zones.
  • Fallback text for no-JavaScript environments.
  • Style Shadow DOM text through CSS parts.
  • Integrate with React through JSX typing.
  • Use native browser internationalization APIs.

Use Cases:

  • Cached server pages that need client‑side date localization.
  • Activity feeds displaying “3 minutes ago” timestamps that update in real time.
  • Countdowns or elapsed time indicators using the duration format.
  • Scheduling UIs where dates must follow the user’s locale and time zone.

How To Use It

Installation

Install the package with npm.

npm install @github/relative-time-element

Import the package in your JavaScript entry file.

import '@github/relative-time-element'

You can also load the browser bundle from a CDN.

<script type="module" src="https://unpkg.com/@github/[email protected]/dist/bundle.js"></script>

Basic Usage

Add a <relative-time> element to your HTML. The element needs a valid ISO 8601 timestamp in datetime and readable fallback text between the tags.

<relative-time datetime="2026-06-17T14:30:00-07:00">
  June 17, 2026
</relative-time>

The browser converts the text into a localized relative time value when the custom element loads. Dates more than 30 days away use an absolute date by default.

Display an Absolute Localized Date

Article pages often need a stable date instead of “time ago” text. Set the format to datetime to display a localized date string.

<relative-time
  datetime="2026-06-17T14:30:00-07:00"
  format="datetime">
  June 17, 2026
</relative-time>

You can refine the date output with date and time formatting attributes.

<relative-time
  datetime="2026-06-17T14:30:00-07:00"
  format="datetime"
  weekday="long"
  month="long"
  day="numeric"
  year="numeric">
  June 17, 2026
</relative-time>

Display Relative Time Only

Activity feeds usually work best with relative phrases. Set the format to relative for output such as “10 minutes ago” or “in 3 hours.”

<relative-time
  datetime="2026-06-17T13:45:00-07:00"
  format="relative">
  June 17, 2026 1:45 PM
</relative-time>

Display a Duration

Countdowns and elapsed time labels need a duration-style output. Set the format to duration to show remaining or elapsed units.

<relative-time
  datetime="2026-06-18T09:00:00-07:00"
  format="duration">
  June 18, 2026 9:00 AM
</relative-time>

The output may include years, months, weeks, days, hours, minutes, and seconds. Zero-value units do not appear by default.

Limit Precision

Long duration strings may feel too detailed in compact UI. Set precision to truncate smaller units.

<relative-time
  datetime="2026-06-18T09:00:00-07:00"
  format="duration"
  precision="minute">
  June 18, 2026 9:00 AM
</relative-time>

A relative value also respects precision. A timestamp less than the selected precision unit away from the current time displays as now.

Change the Relative Time Threshold

Relative output switches to an absolute date after 30 days by default. Change the threshold with an ISO 8601 duration string.

<relative-time
  datetime="2026-09-01T09:00:00-07:00"
  format="relative"
  threshold="P120D">
  September 1, 2026
</relative-time>

Set threshold="P0S" when you always want an absolute date for relative formatting.

<relative-time
  datetime="2026-09-01T09:00:00-07:00"
  format="relative"
  threshold="P0S">
  September 1, 2026
</relative-time>

Force Past or Future Tense

Feeds and countdowns sometimes need one direction only. Set tense to prevent output from crossing into the opposite direction.

<relative-time
  datetime="2026-06-18T09:00:00-07:00"
  format="relative"
  tense="future">
  June 18, 2026
</relative-time>

When tense="future", past values display as now for relative output and 0 seconds for duration output. When tense="past", future values use the same fallback behavior.

Set a Time Zone

Event pages often need a specific time zone instead of the visitor’s local zone. Use an IANA time zone name.

<relative-time
  datetime="2026-06-17T20:00:00Z"
  format="datetime"
  time-zone="America/New_York"
  hour="numeric"
  minute="2-digit"
  time-zone-name="short">
  June 17, 2026 4:00 PM EDT
</relative-time>

The element looks for time-zone on itself first. If the attribute does not exist, it checks parent elements before it falls back to the browser’s default time zone.

Set the Language

The element uses the standard HTML lang attribute for localization. Add it to the element or a parent container.

<div lang="fr">
  <relative-time datetime="2026-06-17T14:30:00-07:00">
    17 juin 2026
  </relative-time>
</div>

If no lang attribute exists on the element or its ancestors, the element defaults to English.

Remove the Title Attribute

The element can add a title attribute for the full timestamp. Add no-title when you plan to provide your own accessible tooltip or visible date label.

<relative-time
  datetime="2026-06-17T14:30:00-07:00"
  no-title>
  June 17, 2026
</relative-time>

Style the Output Text

The element renders its visible text inside Shadow DOM. Style the internal text with the ::part() selector.

relative-time::part(root) {
  color: rebeccapurple;
  font-weight: 600;
}
relative-time::part(root)::selection {
  background: lightgreen;
}

Update the Date with JavaScript

You can set the timestamp through the date property when your app receives a JavaScript Date object.

<relative-time id="last-sync" format="relative">
  Sync time unavailable
</relative-time>
<script type="module">
  import '@github/relative-time-element'
  const syncTime = document.querySelector('#last-sync')
  syncTime.date = new Date()
</script>

Setting date updates the internal datetime value. Setting datetime with a valid ISO 8601 string also updates the date.

React Usage

React needs a JSX type declaration for the custom element. Import the class and declare the element under React.JSX.IntrinsicElements.

import {RelativeTimeElement} from '@github/relative-time-element'
declare module 'react' {
  namespace JSX {
    interface IntrinsicElements {
      'relative-time': React.DetailedHTMLProps<
        React.HTMLAttributes<RelativeTimeElement>,
        RelativeTimeElement
      > &
        Partial<Omit<RelativeTimeElement, keyof HTMLElement>>
    }
  }
}

After the declaration, you can use the element in JSX.

export function PublishedDate() {
  return (
    <relative-time
      datetime="2026-06-17T14:30:00-07:00"
      format="relative"
    >
      June 17, 2026
    </relative-time>
  )
}

Configuration Options

  • datetime (string): Sets the ISO 8601 timestamp represented by the element.
  • format ('datetime' | 'relative' | 'duration' | 'auto' | 'micro' | 'elapsed'): Controls the output mode. auto, micro, and elapsed are deprecated formats.
  • date (Date | null): Sets or reads the represented date through JavaScript.
  • tense ('auto' | 'past' | 'future'): Restricts relative and duration output to a time direction.
  • precision ('year' | 'month' | 'day' | 'hour' | 'minute' | 'second'): Limits the smallest time unit used in relative or duration output.
  • threshold (string): Sets the ISO 8601 duration that controls when relative output turns into an absolute date.
  • prefix (string): Sets the text before absolute dates generated by relative output.
  • formatStyle ('long' | 'short' | 'narrow'): Controls the length of unit labels used by the native Intl formatters.
  • second ('numeric' | '2-digit' | undefined): Controls second display for absolute date formatting.
  • minute ('numeric' | '2-digit' | undefined): Controls minute display for absolute date formatting.
  • hour ('numeric' | '2-digit' | undefined): Controls hour display for absolute date formatting.
  • weekday ('short' | 'long' | 'narrow' | undefined): Controls weekday display for absolute date formatting.
  • day ('numeric' | '2-digit' | undefined): Controls day display for absolute date formatting.
  • month ('numeric' | '2-digit' | 'short' | 'long' | 'narrow' | undefined): Controls month display for absolute date formatting.
  • year ('numeric' | '2-digit' | undefined): Controls year display for absolute date formatting.
  • timeZoneName ('long' | 'short' | 'shortOffset' | 'longOffset' | 'shortGeneric' | 'longGeneric' | undefined): Controls time zone label display.
  • timeZone (string | undefined): Sets the IANA time zone used for date and time output.
  • hourCycle ('h11' | 'h12' | 'h23' | 'h24' | undefined): Controls 12-hour or 24-hour clock output.
  • noTitle (boolean attribute): Prevents the element from adding a title attribute.

Deprecated Formats

  • format="auto": Works as an alias for relative. Migrate to format="relative".
  • format="micro": Outputs compact relative values such as 2w or 30d. Migrate to format="relative" with format-style="narrow" when compact output remains necessary.
  • format="elapsed": Works like duration output with narrow styling. Migrate to format="duration" format-style="narrow".

API Methods

The library does not expose a separate method-based API for common usage. You configure and update each element through attributes and properties.

// Read the represented timestamp as an ISO string.
const currentDateTime = element.datetime;
// Set the represented timestamp with an ISO 8601 string.
element.datetime = '2026-06-17T14:30:00-07:00';
// Read the represented timestamp as a Date object.
const currentDate = element.date;
// Set the represented timestamp with a Date object.
element.date = new Date('2026-06-17T14:30:00-07:00');
// Change the display mode.
element.format = 'duration';
// Limit output precision.
element.precision = 'minute';
// Force future-only output.
element.tense = 'future';
// Change the display time zone.
element.timeZone = 'Europe/London';

Alternatives:

FAQs:

Q: Why does my element still show the fallback date?
A: Check that the script has loaded and that the datetime attribute contains a valid ISO 8601 timestamp. Older browsers may also need custom element and Intl polyfills.

Q: Can I use it with server-rendered HTML?
A: Yes. Place readable fallback text inside the element on the server, then let the browser localize the output after the component loads.

Q: How do I show a fixed date instead of time ago text?
A: Set format="datetime". Add attributes such as weekday, month, day, year, hour, and minute when you need a specific date and time layout.

Q: Can React use the <relative-time> tag directly?
A: Yes. Import the element package and add a JSX intrinsic element declaration when you use TypeScript.

Q: Does the element update automatically, or do I need to call a refresh method?
A: It updates automatically. No manual refresh is required. The element uses a requestAnimationFrame loop to detect when the displayed text should change.

Q: How do I style the displayed text?
A: Use the ::part(root) CSS pseudo-element. For example, relative-time::part(root) { color: blue; } targets the inner <span>.

You Might Be Interested In:


Leave a Reply