A zero-dependency React hook for formatting relative dates.
npm install @nkzw/use-relative-time
Here is an example of how to use useRelativeTime()
to format a date relative to the current time:
import useRelativeTime from '@nkzw/use-relative-time';
export default function BlogPostHeader({ title, time }) {
const timeAgo = useRelativeTime(time);
return (
<>
<h1>{title}</h1>
<time>{timeAgo}</time>
</>
);
}
The time in milliseconds that should be formatted relative to the current time.
The locale used to format the date.
The function to get the current time. You can provide an alternative implementation as source for the current time, like for example if you are syncing the time with a server.
useRelativeTime
depends on Intl.RelativeTimeFormat
. If you are supporting older browsers, you can find a polyfill in Format.JS.
If Intl.RelativeTimeFormat
is not available, useRelativeTime
will gracefully fall back to a basic relative time representation that is not localized, such as "17h" instead of "17 hours ago" or "17 hours from now".