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().
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.
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.
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).
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().
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With