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

The formatDistanceToNow function in date-fns is used to format the distance between a given date and the current date/time in a human-readable format, such as "3 days ago" or "in 5 hours".

To use this function, first install the date-fns package via npm:

index.tsx
npm install date-fns
21 chars
2 lines

Then, import the function into your javascript file:

index.tsx
import { formatDistanceToNow } from 'date-fns';
48 chars
2 lines

You can then call the function, passing in the date to format as a parameter:

index.tsx
const distance = formatDistanceToNow(new Date('2021-12-30T12:00:00'));
console.log(distance); // "3 days ago"
110 chars
3 lines

You can also provide additional options to customize the format of the output, such as specifying the addSuffix option to include "ago" or "in" in the output:

index.tsx
const options = { addSuffix: true };
const distance = formatDistanceToNow(new Date('2022-01-02T12:00:00'), options);
console.log(distance); // "in 2 days"
155 chars
4 lines

gistlibby LogSnag