how to use the intlformatdistance function from date-fns in javascript

To use the intlFormatDistance function from the date-fns library in JavaScript, you need to follow these steps:

  1. Import the necessary functions from the date-fns package:
index.tsx
import {intlFormatDistance, enUS} from 'date-fns';
51 chars
2 lines

Note: The enUS parameter is optional but recommended to ensure proper formatting.

  1. Call the intlFormatDistance function with two dates, and an optional options object:
index.tsx
const result = intlFormatDistance(
  new Date(2010, 0, 1),
  new Date(2019, 8, 1),
  {locale: enUS}
);
console.log(result); // "9 years"
137 chars
7 lines

You can customize the output by passing options to the function:

index.tsx
const result = intlFormatDistance(
  new Date(2010, 0, 1),
  new Date(2019, 8, 1),
  {
    addSuffix: true,
    unit: 'month',
    locale: enUS
  }
);
console.log(result); // "over 109 months ago"
197 chars
11 lines

Here, addSuffix adds the 'ago' or 'in' suffix to the output, and unit specifies the smallest unit to display in the output.

And that's how you can use the intlFormatDistance function from date-fns for formatting time intervals.

gistlibby LogSnag