Staffbase

Hooks

useFormatRelativeTime

A React hook that returns a memoised formatting function for locale-aware relative time, like "3 days ago", "yesterday", or "in 2 weeks".

3 days ago·yesterday·in 2 weeks

Pass a Duration object and get back a human-readable string. Backed entirely by the browser’s Intl.RelativeTimeFormat API — no third-party dependency required.

The hook automatically picks the most significant unit from the Duration object: years first, then months, then weeks, then days. It uses numeric: 'auto', which emits natural-language expressions wherever a locale has them — words like “yesterday”, “today”, “tomorrow”, “last week” — instead of always emitting a numeric value.

Durations at a glance

Every supported duration value rendered for the selected locale.

UnitInputOutput
Years
{ years: -2 }2 years ago
{ years: -1 }last year
{ years: 1 }next year
{ years: 2 }in 2 years
Months
{ months: -2 }2 months ago
{ months: -1 }last month
{ months: 1 }next month
{ months: 2 }in 2 months
Weeks
{ weeks: -2 }2 weeks ago
{ weeks: -1 }last week
{ weeks: 1 }next week
{ weeks: 2 }in 2 weeks
Days
{ days: -2 }2 days ago
{ days: -1 }yesterday
{ days: 0 }today
{ days: 1 }tomorrow
{ days: 2 }in 2 days

Usage

The hook returns a stable format function (memoised with useCallback). Call it anywhere in your render with a Duration object.

Anatomy
import {useFormatRelativeTime} from '@staffbase/design/hooks';

const TimeAgo = ({date}: {date: Date}) => {
  const locale = navigator.language; // or from your i18n context
  const format = useFormatRelativeTime(locale);

  const diffMs = date.getTime() - Date.now();
  const diffDays = Math.round(diffMs / (1000 * 60 * 60 * 24));

  return <time dateTime={date.toISOString()}>{format({days: diffDays})}</time>;
};

Unit priority

The hook resolves the most significant non-zero unit top-down. Provide only the units you want to consider:

Anatomy
const format = useFormatRelativeTime('en-US');

format({years: -1, months: -3, days: -10}); // "last year" — years wins
format({months: -3, days: -10}); // "3 months ago" — months wins
format({weeks: -1, days: -10}); // "last week" — weeks wins
format({days: -3}); // "3 days ago"
format({days: 0}); // "today"

API reference

useFormatRelativeTime(locale)

Name Type Description
locale
stringstring[]Intl.LocaleIntl.Locale[]
A BCP 47 language tag (or list of tags) passed to Intl.RelativeTimeFormat.

Returns a format(duration) function. The Duration object accepts optional years, months, weeks, and days numbers; positive values are in the future, negative in the past.