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

The formatDistanceToNowStrict function is a method from the date-fns library, which determines the distance between a given date and the current date in human-readable language, with the difference being rounded to the nearest integer.

Here's a code snippet that illustrates how to use the formatDistanceToNowStrict function in JavaScript:

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

const date = new Date(2022, 0, 1, 12, 30, 0); // January 1, 2022 at 12:30:00 PM

const distance = formatDistanceToNowStrict(date); // 'in 1 year'

console.log(distance);
230 chars
8 lines

In the above code, we first import the formatDistanceToNowStrict method from date-fns.

Next, we create a Date object for January 1st, 2022 at 12:30:00 PM.

We then call formatDistanceToNowStrict on this date object and store the result in the distance variable.

Finally, we log the distance to the console, which gives the output 'in 1 year'. This indicates that the distance between the current date (i.e., which is when the code is executed) and the provided date object is 1 year.

gistlibby LogSnag