Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js - Parse Date Time Ago

I am saving my date like this in my mongo database:

Thu Oct 25 2018 17:30:03 GMT+0300 (EAT)  

I would like to use moment.js to have in the front end like 1 hour ago or 3 hours ago. How would I go about this?

like image 903
Dng Avatar asked Oct 27 '18 00:10

Dng


People also ask

How do you find time from date in moment?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. moment(). hours();

Is Moment () the same as new date ()?

To get the current date and time, just call moment() with no parameters. var now = moment(); This is essentially the same as calling moment(new Date()) . Note: From version 2.14.0, moment([]) and moment({}) also return now.

Is MomentJS deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

How does moment UTC work?

For moment. utc, the date will be parsed and displayed in local time. By default, date will be shown in local time. In case you need to parse it in UTC, you can make use of this method.


Video Answer


2 Answers

If you're using single locale try

moment('Thu Oct 25 2018 17:30:03 GMT+0300').fromNow(); //eg. 1 day ago, 2 hours ago etc 

or

moment('Thu Oct 25 2018 17:30:03 GMT+0300').fromNow(true); //eg. 1 day, 2 hours 

for more see docs

and:

enter image description here

like image 109
Paweł Avatar answered Nov 02 '22 22:11

Paweł


you can add your date and then compare with the current time:

const timestamp = moment(dateFromDatabase, 'ddd MMM DD YYYY HH:mm:ss GMT Z').fromNow(); 

or you can also use diff()

const timestamp = moment(dateFromDatabase, 'ddd MMM DD YYYY HH:mm:ss GMT Z').diff(Date.now(), 'hours'); 

you can change the measurements using years, months, weeks, days, hours, minutes, and seconds.

For more information, you can take a look on here.

like image 40
Darryl RN Avatar answered Nov 02 '22 22:11

Darryl RN