12

If I use

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

I will get:

a few seconds ago
a minute ago
...

Is it possible to format the output like the following?

00:00 minutes ago
00:01 minutes ago
...
Smoothi
  • 283
  • 1
  • 3
  • 15

4 Answers4

23

You can customize how moment formats relative time for you locale using updateLocale.

Note that the docs says:

If a locale requires additional processing for a 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>

I'm not sure that the code above covers all the case you need, but I think that it can be a good starting point.

VincenzoC
  • 30,117
  • 12
  • 90
  • 112
  • 2
    this is the correct solution, but it was necessary to adjust the relative time threshold thank you :) – Smoothi Jul 18 '16 at 09:41
  • How to format it so it well return, "5 minutes and 30 seconds ago" ? – Wolf Dec 11 '18 at 16:27
  • @Wolf It's quite hard to customize `fromNow` output to get _5 minutes and 30 seconds ago_, take a look [here](https://stackoverflow.com/q/42031436/4131048) and [here](https://stackoverflow.com/q/41508796/4131048) and consider asking a new question referencing this one and showing your attempts. – VincenzoC Dec 12 '18 at 15:47
  • Note that you can replace `'00:' + (number<10 ? '0':'') + number + ' minutes'` with `\`00:${number.toString().padStart(2, "0")} minutes\`` if are writing JavaScript for modern browsers. – 3limin4t0r Oct 19 '21 at 15:30
  • @VincenzoC how would I implement the withoutSuffix parameter if I wanted to remove the suffix? – max Feb 03 '23 at 21:22
  • @max as linked [doc](https://momentjs.com/docs/#/customization/relative-time/) states _The `withoutSuffix` argument will be true if the token will be displayed without a suffix, and false if it will be displayed with a suffix. (The reason for the inverted logic is because the default behavior is to display with the suffix.)_. If you want to remove it you can probably ignore this parameter in your custom function or use `true` as second parameter when using momentjs relative time functions. A dedicated question (not comment) is probably needed for custom issues. – VincenzoC Feb 06 '23 at 09:46
5

You can use fromNow() method.

moment(<time>).fromNow()
moment([2007, 0, 29]).fromNow(); // 4 years ago

If you pass true, you can get the value without the suffix.

moment([2007, 0, 29]).fromNow();     // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years

For more info you can refer source

Kishan Vaghela
  • 7,678
  • 5
  • 42
  • 67
1

As I know, that's impossible using fromNow() function. You can do the following trick:

moment()
    .seconds(moment().diff(moment().startOf("minute"), 'seconds'))
    .format('[00]:ss [minutes ago]');
Alex M
  • 2,756
  • 7
  • 29
  • 35
1

I use this to display relative time. Maybe somehow it would help somebody.

    const Moment = require('moment')
    const _      = require('lodash')    

    const duration = Moment.duration(12460923,'milliseconds')
    const durationAsDays = _.floor(duration.asDays())
    const durationAsHours = _.floor(duration.subtract( durationAsDays, 'days' ).asHours())
    const durationAsMinutes = _.floor(duration.subtract( durationAsHours, 'hours' ).asMinutes())

    let relativeDuration = ''

    if ( durationAsDays > 0  )
        relativeDuration += durationAsDays + 'd '

    if ( durationAsHours > 0 )
        relativeDuration += durationAsHours + 'h '

    if ( durationAsMinutes > 0 )
        relativeDuration += durationAsMinutes + 'm'

    console.log(relativeDuration, durationAsMinutes) // 3h 27m