@nkzw/use-relative-time
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

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

/@nkzw/use-relative-time/

    Package Sidebar

    Install

    npm i @nkzw/use-relative-time

    Weekly Downloads

    149

    Version

    1.1.0

    License

    MIT

    Unpacked Size

    7.14 kB

    Total Files

    13

    Last publish

    Collaborators

    • cpojer