how to use formatdistance from date-fns in javascript

To use formatDistance function from date-fns in JavaScript, first, we need to install the date-fns package in our project using npm or yarn.

npm install date-fns
21 chars
2 lines

Once we installed the date-fns package in our project. We can import the formatDistance function from the package in our JavaScript file.

import { formatDistance } from 'date-fns';
43 chars
2 lines

Now, we can use this formatDistance function to get the distance between two dates in human-readable format. The function takes two arguments. The first argument is the starting date, and the second argument is the ending date to get the distance between them.

const now = new Date();

// 10 days from now
const later = new Date(now.getTime() + 10 * 24 * 60 * 60 * 1000);

const distance = formatDistance(now, later);

console.log(distance);
// output: "10 days"
202 chars
10 lines

We can also pass the third argument to the formatDistance function as an object to provide options like includeSeconds, addSuffix, locale, etc.

const distance = formatDistance(now, later, { addSuffix: true });

console.log(distance);
// output: "in 10 days"
114 chars
5 lines

That's how we can use formatDistance function from date-fns package in JavaScript to get the distance between two dates in human-readable format.

gistlibby LogSnag