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

To use the formatDistanceStrict function from the date-fns library, you need to first install it using a package manager like npm.

npm install date-fns
21 chars
2 lines

Once date-fns is installed, you can import formatDistanceStrict from the module and use it in your code.

index.tsx
const { formatDistanceStrict } = require('date-fns');

const now = new Date();
const past = new Date('2020-09-01');

const distance = formatDistanceStrict(now, past, { addSuffix: true });
console.log(distance);
// Output: "in 2 months"
236 chars
9 lines

In the example above, we imported the formatDistanceStrict function from date-fns and used it to calculate the distance between the current date (now) and a past date (past) in a strict format. We passed an object with an addSuffix property set to true to add a suffix to the output (e.g., "in 2 months" instead of "2 months").

The formatDistanceStrict function takes three arguments:

  • dateToCompare: The date to compare to (usually a past date).
  • date: The date to compare from (usually the current date).
  • options: An object containing formatting options (e.g., addSuffix).

The function returns the distance between the two dates in a strict format (e.g., "1 year", "3 months", "2 days", etc.).

gistlibby LogSnag