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
Yarn add date-fns
Date-fns is bit tricky to use at first.
Here are the steps to use it quickly
Code:
import {formatDistance} from '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
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.
This is where we share our knowledge and insights. Our aim is to impart industry insights to help our website visitors take away valuable information.
Explore More Blog ⟶