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

The formatDistance function from date-fns is used to format the distance between two dates in a human-readable format. Here's an example of how to use it:

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

const date1 = new Date(2021, 0, 1);
const date2 = new Date(2021, 3, 1);

const distance = formatDistance(date1, date2);

console.log(distance); // "3 months"
207 chars
9 lines

In the example above, we first import the formatDistance function from the date-fns library. We then create two Date objects representing January 1st and April 1st of 2021. We then call the formatDistance function with these two dates, which returns a string representing the distance between the two dates in a human-readable format. In this case, it returns "3 months".

You can also provide options to format the output. For example, to use short form distances (e.g. "3 mo." instead of "3 months"), you can provide the addSuffix and short options:

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

const date1 = new Date(2021, 0, 1);
const date2 = new Date(2021, 3, 1);

const distance = formatDistance(date1, date2, {
  addSuffix: true,
  short: true,
});

console.log(distance); // "3 mo. ago"
247 chars
12 lines

In this example, we pass an options object as the third argument to formatDistance. This tells the function to add the suffix "ago" to the output and to use short form distances. The output in this case is "3 mo. ago".

gistlibby LogSnag