Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 491
Mr.Joony Avatar asked Dec 11 '20 14:12

Mr.Joony


2 Answers

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 }
) 
like image 144
Fels Avatar answered Nov 19 '22 21:11

Fels


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`;
like image 1
Kernelio Linusso Avatar answered Nov 19 '22 21:11

Kernelio Linusso