Relative time
A semantic time element that shows an absolute date, then upgrades to text like '3 minutes ago' and refreshes itself.
pnpm dlx shadcn@latest add @haze/relative-time---
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>When to use
- 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.
When not to use
- 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.
Installation
Add the Haze registry to components.json once, then install Relative time with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/relative-timenpx shadcn@latest add @haze/relative-timeyarn dlx shadcn@latest add @haze/relative-timebunx --bun shadcn@latest add @haze/relative-timeFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| datetime | string | 2026-11-21T14:05:00Z | ISO 8601 date-time. Keep an offset or Z so every viewer gets the same moment. |
| locale | string | en | BCP 47 locale used for the absolute and relative text. |
| timeZone | string | UTC | IANA time zone for the absolute text, so server output is deterministic. |
| format | "relative" | "absolute" | "both" | relative | Relative wording, the absolute date only, or both joined as '2 hours ago · Nov 21'. |
| threshold | number | – | Days after which the time stays absolute instead of turning relative. |
| class | string | – | 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.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
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": "http://localhost:4329/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: http://localhost:4329/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.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.