Reputation: 2840
I am using Moment.js and would like to convert unix timestamps to (always) display minutes ago from the current time. E.g.) 4 mins ago, 30 mins ago, 94 mins ago, ect.
Right now I am using:
moment.unix(d).fromNow()
But this does not always display in minutes e.g.) an hour ago, a day ago, ect. I have tried using .asMinutes() but I believe this only words with moment.duration().
Upvotes: 9
Views: 12642
Reputation: 70159
Not sure if this is possible with native Moment methods, but you can easily make your own Moment extension:
moment.fn.minutesFromNow = function() {
return Math.floor((+new Date() - (+this))/60000) + ' mins ago';
}
//then call:
moment.unix(d).minutesFromNow();
Note that other moment methods won't be chainable after minutesFromNow()
as my extension returns a string.
edit:
Extension with fixed plural (0 mins, 1 min, 2 mins):
moment.fn.minutesFromNow = function() {
var r = Math.floor((+new Date() - (+this))/60000);
return r + ' min' + ((r===1) ? '' : 's') + ' ago';
}
You can as well replace "min" with "minute" if you prefer the long form.
Upvotes: 5
Reputation: 3498
Just modify the "find" function in the moment.js code, so that it returns minutes:
from : function (time, withoutSuffix) {
return moment.duration(this.diff(time)).asMinutes();
}
Here's an example.
...or, even better. Just add this as a new function called "fromNowInMinutes".
Upvotes: 2