Relative time
v0.64.0, changelogBetaHow long ago (or how far ahead) a moment is, and the moment itself, through Intl in any locale: for timestamps a server sends.
Install
npx shadcn add @syncrobotic/relative-time Also installs: @syncrobotic/format-number
Overview
When to use
- "Reported 3 minutes ago", "ordered 2 days ago", a log's time column, an axis's ticks.
- The exact time behind a relative one, in a tooltip.
Use something else
- A time of day on a live panel, to the second: Clock time.
- Numbers that are not times: Format number.
Usage rules
- Every "3 minutes ago" and every timestamp a server sends goes through it, so zh-TW and English read the same moment the same way.
- Pass
nowfromuseNow, neverDate.now()in render;minUnit:where the text should not change every second."minute" future:for a device's own timestamps: a clock running fast should not say "in 2 minutes"."clamp" - With next-intl or ICU messages, take
relativePartsand pass the unit and count to your own keys.
API
What the file exports. The source is in the Source sheet above.
- toTime(value: DateInput | null | undefined): number | null
- Ms since the epoch, or null for nothing or a value that is not a date.
- relativeParts(date: DateInput, now: number): { value: number; unit: RelativeUnit }
- The largest unit that fits and a whole count of it, negative in the past.
- formatRelative(date: DateInput, { now, locale, style = "long", minUnit = "second", future = "allow" }: RelativeOptions): string
- How long ago or how far ahead `date` is from `now`, in words: "now", "3 minutes ago", "in 2 days", "3 分鐘前".
- formatAbsolute(date: DateInput, { locale, timeZone, precision = "minute", withZone = false }: AbsoluteOptions = {}): string
- The moment itself, date and 24-hour time: "Nov 27, 2026, 14:02" in English, "2026年11月27日 14:02" in zh-TW.
- formatDuration(ms: number, { locale }: { locale?: string } = {}): string
- A length of time in its two largest units, as Intl writes units: "2 hr 15 min", "45 sec", "2 小時 15 分鐘".
- refreshInterval(date: DateInput, now: number): number
- How often relative text about `date` can change: every second under a minute, every minute under an hour, else hourly.
Types
DateInputRelativeUnitRelativeOptionsAbsoluteOptions
Changelog
- 0.64.02026-12-01Formatted with Prettier (class order sorted); the code is unchanged.
- 0.56.02026-11-27First release:
formatRelative("3 minutes ago", "3 分鐘前";minUnit,future:for a fast clock),"clamp" formatAbsolute(24-hour,precision,timeZone),formatDuration,relativePartsfor your own message keys,toTimeandrefreshInterval.