Skip to main content
/
/
/
useRelativeTime()

useRelativeTime()

import useRelativeTime from "@intility/bifrost-react/hooks/useRelativeTime";
Includes full date tooltip and automatic updates.

The useRelativeTime() hook formats a date as a relative time string (e.g., "5 minutes ago", "in 2 days").

Note: This hook does not automatically update. If you need automatic updates, use the <FormatRelativeTime> component or implement your own update mechanism.

The hook accepts the following parameters:

  • date: (required) a Date object or an ISO formatted date string
  • options: (optional) an object with:

Examples

// e.g., "5 minutes ago", "in 2 days"
const formattedTime = useRelativeTime(myDate);
5 minutes ago

Works with both Date objects and ISO formatted date strings:

const dateObject = new Date("2024-03-04T10:23:11.408Z");
const dateString = "2024-03-04T10:23:11.408Z";

// returns same result
useRelativeTime(dateObject);
useRelativeTime(dateString);
import useRelativeTime from "@intility/bifrost-react/hooks/useRelativeTime";

function MyComponent() {
  const now = new Date();

  // "5 minutes ago"
  const fiveMinutesAgo = useRelativeTime(
    // calculations for demo purposes only;
    // in a real app, you would use a fixed date from your data source instead
    new Date(now.getTime() - 5 * 60 * 1000),
  );

  // "2 hours ago"
  const twoHoursAgo = useRelativeTime(
    new Date(now.getTime() - 2 * 60 * 60 * 1000),
  );

  // "3 days ago"
  const threeDaysAgo = useRelativeTime(
    new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000),
  );

  // "in 2 days"
  const inTwoDays = useRelativeTime(
    new Date(now.getTime() + 2 * 24 * 60 * 60 * 1000),
  );

  return (
    <div>
      <p>{fiveMinutesAgo}</p>
      <p>{twoHoursAgo}</p>
      <p>{threeDaysAgo}</p>
      <p>{inTwoDays}</p>
    </div>
  );
}
5 minutes ago
2 hours ago
3 days ago
in 2 days

Locale

Just like <FormatRelativeTime>, useRelativeTime() follows current bifrost locale (default english).

Use <Bifrost locale={nbNO}> in your app to use norwegian formatting.

Norwegian

<Bifrost locale={nbNO}>
  <MyComponent />
</Bifrost>
for 5 minutter siden
for 2 timer siden
for 3 døgn siden
i overmorgen

Swedish

<Bifrost locale={svSE}>
  <MyComponent />
</Bifrost>
för 5 minuter sedan
för 2 timmar sedan
för 3 dagar sedan
om 2 dagar