# Relative Time

The time since or until a moment, kept current, with the exact time in a tooltip.

Source: [relative-time.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/relative-time.tsx)

```tsx
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { RelativeTime } from "@/components/ui/relative-time";
import { Status } from "@/components/ui/status";
import { people } from "@/examples/data";

export default function RelativeTimeDeployment() {
  const tony = people[0];
  return (
    <div className="grid grid-cols-[auto_auto] gap-x-8 gap-y-1.5 text-sm">
      <span className="text-xs text-faint">Status</span>
      <span className="text-xs text-faint">Created</span>
      <Status variant="success">Ready</Status>
      <div className="flex items-center gap-1.5">
        <RelativeTime date="2026-10-14T15:41:14Z" />
        <span className="text-muted-foreground">by {tony.value}</span>
        <Avatar size="sm">
          <AvatarImage src={tony.image} alt="" />
          <AvatarFallback>{tony.initials}</AvatarFallback>
        </Avatar>
      </div>
    </div>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/relative-time
```

## Usage

```tsx
import { RelativeTime } from "@/components/ui/relative-time";

export function DeployedAt({ createdAt }: { createdAt: string }) {
  return <RelativeTime date={createdAt} />;
}
```

`date` takes a `Date`, a timestamp in milliseconds or a string `Date` can parse, such as an ISO
date. The component renders a `<time>` element whose `dateTime` is the date in ISO format, and
updates its text as time passes.

Within 45 seconds either way, it reads `now`, which also covers small differences between the
server's clock and the browser's. Beyond that, it rounds to the nearest minute, then hour, day,
month and year, so 1 hour and 56 minutes reads `2h ago`. Times in the future read `in 5m`.

Hovering, focusing or tapping the time opens a [Tooltip](https://ui.jarv.is/components/tooltip.md) that shows how long
ago it was in its three largest units, such as `2 years, 3 months, 5 days` or
`1 hour, 56 minutes, 29 seconds`, and the date and time in UTC and in the viewer's own time zone.
Screen readers read the time written out in full, such as `2 hours ago`, followed by the date and
time in the viewer's own time zone, or in the first of `timeZones` when it doesn't list `local`.

### Server rendering

The current time differs between the server and the browser, so on the server the component
renders the date instead, in UTC, such as `Oct 14, 2026`. Once the page hydrates, the date is
replaced with the time relative to the browser's clock. Users without JavaScript see the date, and
a page prerendered at build time never shows how long ago it was built.

A page that the server renders on each request can show the relative time from the start. Pass the
time the page rendered at to `RelativeTimeProvider` as `initialNow`, and send it to the browser with
the page's data, so the server render and hydration describe each date relative to the same moment.
After hydration, the times follow the browser's clock.

```tsx title="src/routes/deployments.tsx"
import { createFileRoute } from "@tanstack/react-router";

import { RelativeTime, RelativeTimeProvider } from "@/components/ui/relative-time";

type Deployment = { id: string; branch: string; createdAt: string };

async function getDeployments(): Promise<Deployment[]> {
  const response = await fetch("https://api.example.com/deployments");
  return response.json();
}

export const Route = createFileRoute("/deployments")({
  loader: async () => ({ deployments: await getDeployments(), renderedAt: Date.now() }),
  component: Deployments,
});

function Deployments() {
  const { deployments, renderedAt } = Route.useLoaderData();
  return (
    <RelativeTimeProvider initialNow={renderedAt}>
      <ul>
        {deployments.map((deployment) => (
          <li key={deployment.id}>
            {deployment.branch}, <RelativeTime date={deployment.createdAt} />
          </li>
        ))}
      </ul>
    </RelativeTimeProvider>
  );
}
```

Leave `initialNow` out of prerendered pages, where it would be the time of the build. The provider
can also set `locale` and `timeZones` for every time inside it.

The time zones show only in the tooltip, which the server never renders, so they always match the
viewer's. All the times on a page share one timer, which fires only when a time's text is due to
change and stops while the tab is hidden.

`formatRelativeTime(date, now?, { locale?, format? })` returns the same text as a string, for places
a component can't go, such as a [Toast](https://ui.jarv.is/components/toast.md)'s title or the page's title. The file is
a client module, so call the function from client code. A server component, as in Next.js, receives
a client reference rather than the function itself.

## Composition

- `RelativeTimeProvider`
  - `RelativeTime`

## Examples

### Formats

`format` sets how much the units are abbreviated.

```tsx
import { RelativeTime } from "@/components/ui/relative-time";

export default function RelativeTimeFormats() {
  return (
    <div className="flex flex-col items-start gap-2 text-sm">
      <RelativeTime date="2026-09-03T08:15:00Z" format="narrow" />
      <RelativeTime date="2026-09-03T08:15:00Z" format="short" />
      <RelativeTime date="2026-09-03T08:15:00Z" format="long" />
    </div>
  );
}
```

### Time zones

`timeZones` lists the tooltip's time zones by their IANA names, with `local` for the viewer's own.

```tsx
import { RelativeTime } from "@/components/ui/relative-time";

export default function RelativeTimeTimeZones() {
  return (
    <p className="text-sm text-muted-foreground">
      Incident opened{" "}
      <RelativeTime
        date="2026-08-21T22:05:31Z"
        timeZones={["America/Los_Angeles", "Europe/London", "Asia/Tokyo", "local"]}
        className="text-foreground"
      />
    </p>
  );
}
```

### Fixed reference

`now` fixes the moment each date is relative to, so the text doesn't change. Use it for
screenshots, tests and times measured from a moment other than the present.

```tsx
import { RelativeTime } from "@/components/ui/relative-time";

const now = "2026-10-01T12:00:00Z";

const events = [
  { name: "Certificate renews", date: "2026-10-29T00:00:00Z" },
  { name: "Maintenance window", date: "2026-10-01T15:30:00Z" },
  { name: "Backup finished", date: "2026-10-01T11:59:40Z" },
  { name: "Last deploy", date: "2026-10-01T09:12:00Z" },
  { name: "Project created", date: "2025-06-18T17:45:00Z" },
];

export default function RelativeTimeFixedNow() {
  return (
    <div className="flex w-full max-w-xs flex-col">
      {events.map((event) => (
        <div
          key={event.name}
          className="flex h-9 items-center justify-between gap-3 border-b border-border-muted text-sm last:border-b-0"
        >
          <span>{event.name}</span>
          <RelativeTime date={event.date} now={now} className="text-muted-foreground" />
        </div>
      ))}
    </div>
  );
}
```

### Labels

`locale` sets how the time is formatted, and `labels` replaces the tooltip's words. Pass only the
labels you want to change.

```tsx
"use client";

import { RelativeTime } from "@/components/ui/relative-time";

export default function RelativeTimeCustomLabels() {
  return (
    <RelativeTime
      date="2026-07-09T06:30:00Z"
      locale="de-DE"
      format="short"
      timeZones={["Europe/Berlin", "UTC"]}
      labels={{
        ago: (duration) => `Vor ${duration}`,
        fromNow: (duration) => `In ${duration}`,
        now: "Gerade eben",
      }}
      className="text-sm"
    />
  );
}
```

### Without a tooltip

Set `tooltip` to `false` where the exact time isn't needed, such as in a long list. With a tooltip,
each time is a stop for the Tab key, so keyboard users can open it, which adds up in a table with a
time on every row.

```tsx
import { RelativeTime } from "@/components/ui/relative-time";

export default function RelativeTimeWithoutTooltip() {
  return (
    <p className="text-sm text-muted-foreground">
      Updated <RelativeTime date="2026-10-30T19:20:00Z" format="long" tooltip={false} />
    </p>
  );
}
```

## Props

| Part | Extends |
| --- | --- |
| `RelativeTime` | `<time>` |
| `RelativeTimeProvider` | — |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### RelativeTime

| Prop         | Type                                                     | Default            | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `date`       | `RelativeTimeDate`                                       | —                  | The time to describe, as a `Date`, a timestamp in milliseconds, or a string that `Date` can parse.                                                                                        |
| `format?`    | `"long" \| "narrow" \| "short"`                          | `"narrow"`         | How much to abbreviate: `2h ago`, `2 hr. ago` or `2 hours ago`.                                                                                                                           |
| `locale?`    | `string`                                                 | `"en-US"`          | The BCP 47 locale that formats the time.                                                                                                                                                  |
| `timeZones?` | `string[]`                                               | `["UTC", "local"]` | The IANA time zones the tooltip lists the time in. `local` is the viewer's own time zone.                                                                                                 |
| `now?`       | `RelativeTimeDate`                                       | —                  | A fixed time to describe `date` relative to, in place of the clock, so the text doesn't change as time passes.                                                                            |
| `tooltip?`   | `boolean`                                                | `true`             | Shows the exact time in a tooltip.                                                                                                                                                        |
| `labels?`    | `RelativeTimeLabels`                                     | —                  | Replaces the tooltip's words. Pass only the labels you want to change.                                                                                                                    |
| `className?` | `string`                                                 | —                  | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —                  | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —                  | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### RelativeTimeProvider

| Prop          | Type               | Default | Description                                                                                                                                                                                                           |
| ------------- | ------------------ | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `initialNow?` | `RelativeTimeDate` | —       | The time the server rendered the page. The server render and hydration show times relative to it, and then the times follow the browser's clock. Leave it out on prerendered pages, where it would be the build time. |
| `locale?`     | `string`           | —       | The BCP 47 locale for every Relative Time inside.                                                                                                                                                                     |
| `timeZones?`  | `string[]`         | —       | The time zones every Relative Time inside lists in its tooltip.                                                                                                                                                       |
| `children?`   | `React.ReactNode`  | —       |                                                                                                                                                                                                                       |

### RelativeTimeLabels

`labels` takes any of these, and keeps the English default for the rest.

| Property   | Type                             | Default      | Description                                                                            |
| ---------- | -------------------------------- | ------------ | -------------------------------------------------------------------------------------- |
| `ago?`     | `((duration: string) => string)` | —            | Formats a time in the past, given how long ago it was, as in `1 hour, 56 minutes ago`. |
| `fromNow?` | `((duration: string) => string)` | —            | Formats a time in the future, given how long until it, as in `in 1 hour, 56 minutes`.  |
| `now?`     | `string`                         | `"Just now"` | Shown in place of the duration when the time is less than a second away.               |
