Using date-fns quickly Dates in react

Brief: Date-fns is a package used to display a date string from date object, it provide better performance thena date object. It is much easier to use .

 in our use case it mostly use to convert timestamp normal dates in in the below example we have used to calculate distance from current time example: 3 days ago

Installation:

Yarn add date-fns

Tutorial

Date-fns is bit tricky to use at first.

Here are the steps to use it quickly

Code:

import {formatDistancefrom 'date-fns';
const newsUploadTime = formatDistance(
    new Date(item?.created_at),
    new Date(),
    {
      addSuffix: true,
    },
  );

Here item.created_at is a ISO timestamp e.g. 2022-04-17T16:29:03+00:00

It is needed to create a new date object from this timestamp To use with dateFNS functions.

Format distance take 2 parameters   first is main date and second is the current date to compare with

Link: https://date-fns.org/v2.28.0/docs/formatDistance

For using it to generate a normal date string. Eg. 2022-04-20, 22 march 2022

Code:

Const date = item.created_at;
format(parseISO(date), "dd-MM-yyyy"));

As we can see parseISO function is used to get the date object from the timestamp string.