React: Converting mongoDB date to human readable date



A document stored in MongoDB has a “createdAt” property, which contains a timestamp. Here we have an example of the timestamp:

createdAt: 2021-10-26T12:24:33.433+00:00

Considering this date is today, how can I reproduce the following behavior?:

  • Display this date as “Today at 12:24 PM”
  • Tomorrow, display this date as “Yesterday at 12:24 PM”
  • From the day after tomorrow and beyond, display it as “26/10/2021 at 12:24 PM”

I tried using the JavaScript’s Date instance to compare both strings but I got into some trouble trying to convert the strings properly. I was wondering if there’s any library that could ease the process or some conventional way to do it.

Answer

Since you mention using React, I assume that you have a Node running there somewhere. Maybe a create-react-app backend? I will also assume ESM.

You would achieve something like this with date-fns; see docs at https://date-fns.org/v2.25.0/docs/formatDistance

$ npm i date-fns First, install dependency, then test it like below:

import formatDistance from 'date-fns/formatDistance'

function TestComponent() {
   const dateStr = "2021-10-26T12:24:33.433+00:00";
   const str = formatDistance(
       new Date(dateStr),
       new Date()
   );
   return <h1>{str}</h1>
}


Source: stackoverflow