Sort relative time at time

If i use

moment().startOf("minute").fromNow();

I will get:

a few seconds ago
a minute ago
...

Can I format the output as follows?

00:00 minutes ago
00:01 minutes ago
...
+5
source share
2 answers

You can configure how relative time is in the format format for your locale using updateLocale.

Please note that the docs indicate:

If the locale requires additional processing for the token, it can set the token as a function with the following signature. The function should return a string.

function (number, withoutSuffix, key, isFuture) {
    return string;
}

In your case, you can do something like this:

var m1 = moment().subtract(5, 'm');
var m2 = moment().subtract(15, 's');

console.log(m1.fromNow());
console.log(m2.fromNow());

moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s: function (number, withoutSuffix, key, isFuture){
            return '00:' + (number<10 ? '0':'') + number + ' minutes';
        },
        m:  "01:00 minutes",
        mm: function (number, withoutSuffix, key, isFuture){
            return (number<10 ? '0':'') + number + ':00' + ' minutes';
        },
        h:  "an hour",
        hh: "%d hours",
        d:  "a day",
        dd: "%d days",
        M:  "a month",
        MM: "%d months",
        y:  "a year",
        yy: "%d years"
    }
});


console.log(m1.fromNow());
console.log(m2.fromNow());
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
Run codeHide result

I'm not sure if the code above covers everything you need, but I think this might be a good starting point.

+9
source

, fromNow(). :

moment()
    .seconds(moment().diff(moment().startOf("minute"), 'seconds'))
    .format('[00]:ss [minutes ago]');
0

Source: https://habr.com/ru/post/1680668/


All Articles