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
TSX
// 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:
TSX
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);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
TSX
<Bifrost locale={nbNO}>
<MyComponent />
</Bifrost>for 5 minutter siden
for 2 timer siden
for 3 døgn siden
i overmorgen
Swedish
TSX
<Bifrost locale={svSE}>
<MyComponent />
</Bifrost>för 5 minuter sedan
för 2 timmar sedan
för 3 dagar sedan
om 2 dagar