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?
The moment(). hour() Method is used to get the hours from the current time or to set the hours. moment(). hours();
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.
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.
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.
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:
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.
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