Skip to content
Advertisement

Moment.js always returns ‘a few seconds ago’

From the docs:

“To get the current date and time, just call moment() with no parameters.

JavaScript

This is essentially the same as calling moment(new Date()).

Note: From version 2.14.0, moment([]) and moment({}) also return now. They used to default to start-of-today before 2.14.0, but that was arbitrary so it was changed.”

I have tried both

JavaScript

and also

JavaScript

and a lot of other options. Upon page refresh, the time always displays ‘a few seconds ago’.

Thanks for your help!

Advertisement

Answer

The fromNow method, compares a date you pass to moment() to the date and time it is now, when you call that method.

It will always return a few seconds ago if you pass nothing or new Date() to moment() because it will be comparing it to moment’s version of now (probably calling new Date() at some point). The difference between these two dates will always be equal or a few milliseconds difference.

If you are looking to display the time difference from a date, you need to pass the comparison date into moment like so:

JavaScript

Sample outputs and similar comparison methods can be found on the moment docs http://momentjs.com/docs/#/displaying/fromnow/

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement