Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

javascript - Format relative time in momentJs

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
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...