1.1.0 • Published 2 months ago

@nkzw/use-relative-time v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

@nkzw/use-relative-time

A zero-dependency React hook for formatting relative dates.

Installation

npm install @nkzw/use-relative-time

Usage

useRelativeTime()

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>
    </>
  );
}

Parameters

time: number

The time in milliseconds that should be formatted relative to the current time.

locale: Intl.UnicodeBCP47LocaleIdentifier, defaults to 'en'

The locale used to format the date.

dateNow: () => number, defaults to Date.now

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.

Notes

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".

1.1.0

2 months ago

1.0.0

7 months ago

0.0.2

7 months ago

0.0.1

7 months ago