Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the output of a fromNow call?

I use moment.js to get relative time. It returns, for example, "6 hours ago". But I would like to get the short version like "6h".

I read the doc: http://momentjs.com/docs/#/customization/relative-time/

But if I change:

moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s  : 'a few seconds',
        ss : '%d seconds',
        m:  "a minute",
        mm: "%d 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"
    }
});

to

moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s",
        s  : 'a few seconds',
        ss : '%d h',
        m:  "a minute",
        mm: "%d m",
        h:  "an hour",
        hh: "%d h",
        d:  "a day",
        dd: "%d d",
        M:  "a month",
        MM: "%d m",
        y:  "a year",
        yy: "%d y"
    }
});

I get the error:

Cannot read property 'humanize' of undefined at Moment.from (moment.js:3313)

When I call

moment(value).fromNow()

Here, value is a date as Date type

Is it possible to get short format version with moment.js ?

like image 947
Pierre-Luc BLOT Avatar asked Sep 17 '25 09:09

Pierre-Luc BLOT


1 Answers

I assume your issue is the format string. I used 'hh':

moment.updateLocale('en', {
    relativeTime : {
        future: "in %s",
        past:   "%s ago",
        s  : 'a few seconds',
        ss : '%d seconds',
        m:  "a minute",
        mm: "%d minutes",
        h:  "an hour",
        hh: "%dh",
        d:  "a day",
        dd: "%d days",
        M:  "a month",
        MM: "%d months",
        y:  "a year",
        yy: "%d years"
    }
});

//
// compute six hours ago...
//
 var value = new Date();
value.setHours(value.getHours() - 6);


console.log('With \'hh\' format string: ' + moment(value).fromNow('hh'));
console.log('With no format: ' + moment(value).fromNow());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
like image 84
gaetanoM Avatar answered Sep 19 '25 05:09

gaetanoM