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?:
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.
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>
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.