Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 670
Scott Bartell Avatar asked Aug 26 '12 22:08

Scott Bartell


People also ask

How do you format time in a moment?

We can parse a string representation of date and time by passing the date and time format to the moment function. const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console. log(parsed.

How can I get previous date in moment?

Just like this: moment(). subtract(1, 'days') . It will give you the previous day with the same exact current time that is on your local pc. Save this answer.

How do you get a timestamp moment in Unix?

We can use the moment. unix() function to parse unix timestamps (seconds). The moment. unix() function is used to create a moment using Unix Timestamp, seconds since the Unix Epoch (Jan 1 1970 12AM UTC).

What is Moment () Unix ()?

The moment(). unix() function is used to get the number of seconds since the Unix Epoch. Basically the Unix time is a system for describing a point in time. Syntax: moment().


1 Answers

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

like image 194
Fabrício Matté Avatar answered Nov 15 '22 17:11

Fabrício Matté