I searched around the documentions of some popular time parsing and formatting libraries like Day.js
and date-fns
, but I didn't really get it.
My Node.js
backend queries the datetime of creation of a record in my MySQL
database and sends it to the frontend (im using React
). On the frontend I want to find the time differnce between the date from the database (which looks like this 2020-12-04T15:39:40.000Z
and is already parsed from json to a javscript object) and the current datetime.
Social media sites for example have something like "postet 2 days ago".
I have seen solutions using no libraries just vanilla javascript, but they seem to long and I didn't really understand them. I would like to use a library which streamlines this.
What do you think would be the best approach?
date-fns has a built in localized function to output a string like that:
https://date-fns.org/v2.16.1/docs/formatDistance
So you could use:
formatDistance(
new Date('2020-12-04T15:39:40.000Z'),
new Date(),
{ addSuffix: true }
)
You can use diff method of Moment.js library. Your code may be something like this:
diffDays = currentDate.diff(databaseDate, "days");
diffString = `posted ${diffDays} days ago`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With