useRelativeTime()
import useRelativeTime from "@intility/bifrost-react/hooks/useRelativeTime";useRelativeTime()
Go to top
Also see
<FormatRelativeTime> componentIncludes 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) aDateobject or an ISO formatted datestringoptions: (optional) an object with:locale: (optional) override the current localeoptions: (optional)Intl.RelativeTimeFormatOptions
Examples
// e.g., "5 minutes ago", "in 2 days" const formattedTime = useRelativeTime(myDate);
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> ); }
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>
Swedish
<Bifrost locale={svSE}> <MyComponent /> </Bifrost>