Reputation: 584
From the docs:
"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. They used to default to start-of-today before 2.14.0, but that was arbitrary so it was changed."
I have tried both
moment().fromNow()
and also
moment(new Date()).fromNow()
and a lot of other options. Upon page refresh, the time always displays 'a few seconds ago'.
Thanks for your help!
Upvotes: 3
Views: 13518
Reputation: 2056
Moment's duration's humanize function allows you to pass thresholds https://momentjs.com/docs/#/durations/humanize
By default you will get:
moment.duration(35 * 1000).humanize() // a few seconds
If you pass threshold for ss
moment.duration(35 * 1000).humanize({ss: 1}) // 35 seconds
Upvotes: 0
Reputation: 3439
In order to get exactly how many seconds ago, you can do something like this.
function timeAgo(time) {
moment.updateLocale('en', {
relativeTime: {
future: "in %s",
past: "%s ago",
s: number=>number + "s ago",
ss: '%ds ago',
m: "1m ago",
mm: "%dm ago",
h: "1h ago",
hh: "%dh ago",
d: "1d ago",
dd: "%dd ago",
M: "a month ago",
MM: "%d months ago",
y: "a year ago",
yy: "%d years ago"
}
});
let secondsElapsed = moment().diff(time, 'seconds');
let dayStart = moment("2018-01-01").startOf('day').seconds(secondsElapsed);
if (secondsElapsed > 300) {
return moment(time).fromNow(true);
} else if (secondsElapsed < 60) {
return dayStart.format('s') + 's ago';
} else {
return dayStart.format('m:ss') + 'm ago';
}
},
The result will be
2s ago
Upvotes: 6
Reputation: 2979
You are using moment(new Date())
which is going to return now
and then calling fromNow()
. So the time difference is always going to be 0 seconds (or a few milliseconds) so thats what is getting displayed.
You should pass in some date to moment like:
moment("12-25-1995", "MM-DD-YYYY");
And then call fromNow()
on it so as to get time difference between that date and now
.
Upvotes: 0
Reputation: 195
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:
var date = '2016-04-09 02:57:00';
var diff = moment(date).fromNow(); // 'A year ago'
Sample outputs and similar comparison methods can be found on the moment docs http://momentjs.com/docs/#/displaying/fromnow/
Upvotes: 8