Relative Time Formatting

How to display timestamps as relative time like '3 hours ago' or 'in 5 minutes'. Covers Intl.RelativeTimeFormat, libraries, and implementation strategies.

Format

3 hours ago

Detailed Explanation

Relative time formatting converts an absolute timestamp into a human-friendly description of how long ago (or how far in the future) an event occurred. Examples include "3 hours ago," "just now," "yesterday," and "in 2 weeks." This format is ubiquitous in social media feeds, notification lists, and activity logs.

Native browser API — Intl.RelativeTimeFormat:

const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

rtf.format(-1, "day")      // "yesterday"
rtf.format(-3, "hour")     // "3 hours ago"
rtf.format(2, "week")      // "in 2 weeks"
rtf.format(-1, "minute")   // "1 minute ago"
rtf.format(0, "second")    // "this second" (with numeric: "auto")

The Intl.RelativeTimeFormat API handles localization automatically. Pass "ja" for Japanese, "fr" for French, and so on. The numeric: "auto" option produces natural text like "yesterday" instead of "1 day ago."

Calculating the right unit:

The API requires you to determine the unit and value yourself. Here is a practical function:

function relativeTime(timestamp) {
  const now = Date.now();
  const diff = timestamp - now;
  const seconds = Math.round(diff / 1000);
  const minutes = Math.round(diff / 60000);
  const hours = Math.round(diff / 3600000);
  const days = Math.round(diff / 86400000);

  const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

  if (Math.abs(seconds) < 60) return rtf.format(seconds, "second");
  if (Math.abs(minutes) < 60) return rtf.format(minutes, "minute");
  if (Math.abs(hours) < 24) return rtf.format(hours, "hour");
  if (Math.abs(days) < 30) return rtf.format(days, "day");
  // extend for months, years as needed
}

Common pitfalls:

Relative time changes as the user views the page. For dynamic updates, use setInterval to recompute the label, but debounce to avoid unnecessary re-renders. For server-rendered pages, the relative time computed on the server may be stale by the time the client sees it — hydrate with the actual timestamp and compute client-side.

When to use absolute vs. relative: Use relative time for recent events (within the last week). For older events, switch to an absolute format like "Jan 15, 2024." This prevents confusing labels like "387 days ago."

Use Case

Social media feeds and notification panels use relative timestamps because '5 minutes ago' is immediately understandable, while '2024-01-15T09:25:00Z' requires mental calculation.

Try It — Timestamp Converter

Open full tool