Moment.js unix timestamp to display the time back is always in minutes

I am using Moment.js and would like to convert unix timestamps to (always) display minutes ago from the current time. For example, 4 minutes ago, 30 minutes ago, 94 minutes ago, ect.

Now I am using:

moment.unix(d).fromNow() 

But this is not always displayed in minutes, for example, an hour ago, a day ago, etc. I tried using .asMinutes (), but I only believe in words with the moment.duration () parameter.

+7
source share
2 answers

Not sure if this is possible with Moment's own methods, but you can easily create 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 will not be bound after minutesFromNow() , since my extension returns a string.

change

Fixed plural extension (0 min s , 1 min, 2 min s ):

 moment.fn.minutesFromNow = function() { var r = Math.floor((+new Date() - (+this))/60000); return r + ' min' + ((r===1) ? '' : 's') + ' ago'; } 

You can also replace “min” with “minute” if you prefer a long shape.

Fiddle

+4
source

Just change the "find" function in the moment.js file to return minutes:

 from : function (time, withoutSuffix) { return moment.duration(this.diff(time)).asMinutes(); } 

Here is an example .

... or, even better. Just add this as a new feature called "fromNowInMinutes".

+2
source

All Articles