Local Time
Shows a timestamp in the viewer's own time zone, or as “5 minutes ago”. The server renders UTC inside <time dateTime>, so the first paint and crawlers get a real date, then the text swaps after hydration.
Preview
- Starts
- Date
- Full
- Posted
Install
npx shadcn@latest add @dxbh-ui/local-time
Add the @dxbh-ui registry to components.json once:
{
"registries": {
"@dxbh-ui": "https://ui.dxbh.dev/r/{name}.json"
}
}Usage
"use client";
import { useState } from "react";
import { LocalTime, RelativeTime } from "@/components/ui/local-time/local-time";
export default function LocalTimeDemo() {
// Fixed per mount so the demo shows a stable event a few hours out.
const [event] = useState(() => Math.ceil(Date.now() / 3_600_000) * 3_600_000 + 3 * 3_600_000);
const [posted] = useState(() => Date.now() - 42 * 60_000);
return (
<dl className="grid w-full max-w-xs grid-cols-[auto_1fr] gap-x-6 gap-y-3 text-sm">
<dt className="text-muted-foreground">Starts</dt>
<dd><LocalTime value={event} format="time" /></dd>
<dt className="text-muted-foreground">Date</dt>
<dd><LocalTime value={event} format="date" /></dd>
<dt className="text-muted-foreground">Full</dt>
<dd><LocalTime value={event} /></dd>
<dt className="text-muted-foreground">Posted</dt>
<dd><RelativeTime value={posted} /></dd>
</dl>
);
}Props
| Prop | Type | Default |
|---|---|---|
value*A Date, an ISO string or epoch ms. | Date | string | number | — |
formatWhich fields to show (LocalTime). | "time" | "date" | "datetime" | "datetime" |
localeBCP 47 locale for the hydrated text. Defaults to the viewer's. | string | — |
optionsFull control over the hydrated text; overrides format (LocalTime). | Intl.DateTimeFormatOptions | — |
Polish
- Renders a semantic <time dateTime> instead of a span with suppressHydrationWarning.
- The UTC fallback is built by hand so Node and every browser produce identical markup, and it carries the same fields as the local text.
- Hydration-safe through useClientValue; RelativeTime ticks on the shared useNow minute clock, so many timestamps share one timer.
- tabular-nums keeps digits from jittering. Text changes without animation.
- Locale and Intl options are props instead of a hard-coded en-US.
- Invalid dates render nothing rather than “Invalid Date”.
Source
"use client";
import type { HTMLAttributes } from "react";
import { cn } from "@/lib/utils";
import { useClientValue } from "@/hooks/use-client-value";
import { useNow } from "@/hooks/use-now";
export type TimeValue = Date | string | number;
export type TimeFormat = "time" | "date" | "datetime";
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
export function toDate(value: TimeValue): Date {
return value instanceof Date ? value : new Date(value);
}
/**
* The UTC rendering used on the server and during hydration. Built by hand,
* not with Intl, so Node and every browser produce the same string. It
* carries the same fields as the local rendering so nothing appears late.
*/
export function formatUtc(date: Date, format: TimeFormat = "datetime"): string {
const h = date.getUTCHours();
const time = `${h % 12 || 12}:${String(date.getUTCMinutes()).padStart(2, "0")} ${h >= 12 ? "PM" : "AM"} UTC`;
const day = `${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}`;
if (format === "time") return time;
if (format === "date") return `${day}, ${date.getUTCFullYear()}`;
return `${day}, ${time}`;
}
const PRESETS: Record<TimeFormat, Intl.DateTimeFormatOptions> = {
time: { hour: "numeric", minute: "2-digit" },
date: { year: "numeric", month: "short", day: "numeric" },
datetime: { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" },
};
/** Formats in the viewer's own time zone. Browser only. */
export function formatLocal(date: Date, format: TimeFormat = "datetime", locale?: string, options?: Intl.DateTimeFormatOptions) {
return date.toLocaleString(locale, options ?? PRESETS[format]);
}
export type LocalTimeProps = Omit<HTMLAttributes<HTMLTimeElement>, "children"> & {
/** A Date, an ISO string or epoch ms. */
value: TimeValue;
/** Which fields to show. */
format?: TimeFormat;
/** BCP 47 locale for the hydrated text. Defaults to the viewer's. */
locale?: string;
/** Full control over the hydrated text; overrides `format`. */
options?: Intl.DateTimeFormatOptions;
};
/**
* A timestamp in the viewer's time zone. The server renders UTC inside a
* `<time dateTime>`, so crawlers and the first paint get a real date, then
* the text swaps to local time after hydration.
*/
export function LocalTime({ value, format = "datetime", locale, options, className, ...props }: LocalTimeProps) {
const date = toDate(value);
const valid = !Number.isNaN(date.getTime());
const local = useClientValue<string | null>(
() => (valid ? formatLocal(date, format, locale, options) : null),
null,
);
if (!valid) return null;
return (
<time dateTime={date.toISOString()} className={cn("tabular-nums", className)} {...props}>
{local ?? formatUtc(date, format)}
</time>
);
}
const UNITS: [Intl.RelativeTimeFormatUnit, number][] = [
["year", 365 * 86_400_000],
["month", 30 * 86_400_000],
["week", 7 * 86_400_000],
["day", 86_400_000],
["hour", 3_600_000],
["minute", 60_000],
];
/** "3 hours ago", "in 2 days". Under a minute reads as "now". */
export function formatRelative(ms: number, locale?: string): string {
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
const abs = Math.abs(ms);
for (const [unit, size] of UNITS) {
if (abs >= size) return rtf.format(Math.trunc(ms / size), unit);
}
return rtf.format(0, "second");
}
export type RelativeTimeProps = Omit<LocalTimeProps, "format" | "options">;
/**
* "5 minutes ago", kept current by the shared minute clock. Renders the UTC
* date on the server; the exact local time sits in the title.
*/
export function RelativeTime({ value, locale, className, title, ...props }: RelativeTimeProps) {
const date = toDate(value);
const now = useNow(60_000);
const valid = !Number.isNaN(date.getTime());
if (!valid) return null;
return (
<time
dateTime={date.toISOString()}
title={title ?? (now === null ? formatUtc(date) : formatLocal(date, "datetime", locale, { dateStyle: "medium", timeStyle: "short" }))}
className={cn("tabular-nums", className)}
{...props}
>
{now === null ? formatUtc(date) : formatRelative(date.getTime() - now, locale)}
</time>
);
}Extracted from anidub/apps/web/src/components/local-time.tsx at a950c62.