48

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Dng
  • 633
  • 1
  • 8
  • 14
  • First, [parse](https://momentjs.com/docs/#/parsing/string-format/) the date (you may want to look into [moment's timezone extension](https://momentjs.com/timezone/)). After parsing it, you can find a [relative time](https://momentjs.com/docs/#/displaying/fromnow/) fairly easily. – c1moore Oct 27 '18 at 00:33
  • Actually, since you have the UTC offset, you probably don't need the timezone extension. – c1moore Oct 27 '18 at 00:37

2 Answers2

114

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

Paweł
  • 2,144
  • 1
  • 18
  • 25
6

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.

Darryl RN
  • 7,432
  • 4
  • 26
  • 46