# Relative time

> A semantic time element that shows an absolute date, then upgrades to text like '3 minutes ago' and refreshes itself.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/relative-time`
- File: `src/components/haze/ui/relative-time.astro`
- npm dependencies: none
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/relative-time

## Use when
- Activity feeds, comments and logs show when something happened and recency matters more than the exact date.
- Timestamps must stay readable and correct in the HTML before any script runs.
- Future events such as a deadline or a scheduled release need 'in 2 days' wording.

## Avoid when
- The exact date and time is the point, as in invoices or audit exports; render a plain time element instead.
- The user picks a date or time; use datetime-picker or time-picker.

## Alternatives
- [timeline](https://hazeui.com/ui/timeline.md)
- [datetime-picker](https://hazeui.com/ui/datetime-picker.md)
- [time-picker](https://hazeui.com/ui/time-picker.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| datetime | `string` | 2026-11-21T14:05:00Z | no | ISO 8601 date-time. Keep an offset or Z so every viewer gets the same moment. |
| locale | `string` | en | no | BCP 47 locale used for the absolute and relative text. |
| timeZone | `string` | UTC | no | IANA time zone for the absolute text, so server output is deterministic. |
| format | `"relative" \| "absolute" \| "both"` | relative | no | Relative wording, the absolute date only, or both joined as '2 hours ago · Nov 21'. |
| threshold | `number` |  | no | Days after which the time stays absolute instead of turning relative. |
| class | `string` |  | no | Classes for the time element. |

## Accessibility
- The datetime attribute keeps the value machine-readable; the visible text is what a screen reader announces.
- It is not a live region, so the 30-second refresh does not interrupt reading.
- Without script the absolute date stays in place; once upgraded, the absolute date moves to the title attribute.

## Agent prompts

### Install and use

Install the Haze UI component "Relative time" with `npx shadcn@latest add @haze/relative-time`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import RelativeTime from "@/components/haze/ui/relative-time.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/relative-time.md

### Customize with real content

Adapt the Haze relative-time ui for our product. Replace the demo values of these props with our real content: datetime, locale, timeZone, format, threshold, class. Keep the layout, the heading level rules and these accessibility details: The datetime attribute keeps the value machine-readable; the visible text is what a screen reader announces. It is not a live region, so the 30-second refresh does not interrupt reading. Without script the absolute date stays in place; once upgraded, the absolute date moves to the title attribute. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using relative-time, check it fits: use it when activity feeds, comments and logs show when something happened and recency matters more than the exact date.; timestamps must stay readable and correct in the html before any script runs.; future events such as a deadline or a scheduled release need 'in 2 days' wording.. Avoid it when the exact date and time is the point, as in invoices or audit exports; render a plain time element instead.; the user picks a date or time; use datetime-picker or time-picker.. Alternatives: @haze/timeline, @haze/datetime-picker, @haze/time-picker.

## Example requests that should lead here
- Show 'edited 5 minutes ago' under each comment.
- Label a deploy log entry with relative time and the date next to it.
- Keep release dates absolute once they are more than 30 days old.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Props {
  datetime?: string;
  locale?: string;
  timeZone?: string;
  format?: "relative" | "absolute" | "both";
  threshold?: number;
  class?: string;
}

const {
  datetime = "2026-11-21T14:05:00Z",
  locale = "en",
  timeZone = "UTC",
  format = "relative",
  threshold,
  class: className,
} = Astro.props;

const date = new Date(datetime);
const valid = !Number.isNaN(date.getTime());
let absolute = datetime;
if (valid) {
  try {
    absolute = new Intl.DateTimeFormat(locale, { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hourCycle: "h23", timeZone }).format(date);
  } catch {
    absolute = date.toISOString();
  }
}
---

<time
  data-haze-relative-time
  datetime={datetime}
  data-locale={locale}
  data-time-zone={timeZone}
  data-format={format}
  data-threshold={threshold}
  data-absolute={absolute}
  class={cn("tabular-nums", className)}>{absolute}</time>

<script>
  const SECOND = 1000;
  const MINUTE = 60 * SECOND;
  const HOUR = 60 * MINUTE;
  const DAY = 24 * HOUR;
  let timer: number | undefined;

  function relative(diff: number, locale: string): string {
    const abs = Math.abs(diff);
    const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
    if (abs < MINUTE) return rtf.format(0, "second");
    if (abs < HOUR) return rtf.format(Math.trunc(diff / MINUTE), "minute");
    if (abs < DAY) return rtf.format(Math.trunc(diff / HOUR), "hour");
    if (abs < 30 * DAY) return rtf.format(Math.trunc(diff / DAY), "day");
    // Average calendar units, rounded to the nearest, so 364 days reads as a year and not "12 months".
    const sign = diff < 0 ? -1 : 1;
    const months = Math.max(1, Math.round(abs / (30.4375 * DAY)));
    if (months < 12) return rtf.format(sign * months, "month");
    return rtf.format(sign * Math.max(1, Math.round(abs / (365.25 * DAY))), "year");
  }

  // Updates one element and returns its age in ms (Infinity when it stays absolute).
  function update(el: HTMLTimeElement): number {
    const date = new Date(el.getAttribute("datetime") ?? "");
    if (Number.isNaN(date.getTime())) return Infinity;
    const locale = el.dataset.locale || "en";
    const timeZone = el.dataset.timeZone || "UTC";
    const format = el.dataset.format || "relative";
    const absolute = el.dataset.absolute ?? el.textContent ?? "";
    const diff = date.getTime() - Date.now();
    const threshold = el.dataset.threshold ? Number(el.dataset.threshold) : NaN;
    if (format === "absolute" || (!Number.isNaN(threshold) && Math.abs(diff) > threshold * DAY)) {
      el.textContent = absolute;
      el.removeAttribute("title");
      return Infinity;
    }
    let text = relative(diff, locale);
    if (format === "both") {
      try {
        const yearOf = new Intl.DateTimeFormat(locale, { year: "numeric", timeZone });
        const sameYear = yearOf.format(new Date()) === yearOf.format(date);
        const short = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", year: sameYear ? undefined : "numeric", timeZone }).format(date);
        text = `${text} · ${short}`;
      } catch {
        /* keep the relative text only */
      }
    }
    if (el.textContent !== text) el.textContent = text;
    el.title = absolute;
    return Math.abs(diff);
  }

  function tick() {
    window.clearTimeout(timer);
    let youngest = Infinity;
    document.querySelectorAll<HTMLTimeElement>("time[data-haze-relative-time][data-enhanced]").forEach((el) => {
      youngest = Math.min(youngest, update(el));
    });
    if (youngest === Infinity || document.hidden) return;
    const wait = youngest < HOUR ? 30 * SECOND : youngest < DAY ? 5 * MINUTE : HOUR;
    timer = window.setTimeout(tick, wait);
  }

  const init = () => {
    document.querySelectorAll<HTMLTimeElement>("time[data-haze-relative-time]").forEach((el) => {
      if (el.hasAttribute("data-enhanced")) return;
      el.setAttribute("data-enhanced", "");
    });
    tick();
  };
  init();
  if (!document.documentElement.hasAttribute("data-haze-relative-time-listener")) {
    document.documentElement.setAttribute("data-haze-relative-time-listener", "");
    document.addEventListener("astro:page-load", init);
    document.addEventListener("visibilitychange", () => { if (!document.hidden) tick(); });
  }
</script>
```
