Scott Bartell
Scott Bartell

Reputation: 2840

Moment.js unix timestamp to display time ago always in minutes

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

Answers (2)

Fabrício Matté
Fabrício Matté

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();

Fiddle

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.

Fiddle

Upvotes: 5

Greg Ross
Greg Ross

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

Related Questions