How do I get "time ago" with a date provided by mysql?

Viewed 9251

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?

2 Answers

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`;
Related