How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

后端 未结 25 1626
遥遥无期
遥遥无期 2020-11-22 12:57

The question is how to format a JavaScript Date as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.

e.g.<

25条回答
  •  长发绾君心
    2020-11-22 13:13

    Although the question was asked quite long time ago, writing this answer with hope it will help somebody.

    Pass the date you want to start to count from. Using moment().fromNow() of momentjs: (See more information here)

    getRelativeTime(date) {
        const d = new Date(date * 1000);
        return moment(d).fromNow();
    }
    

    If you want to change information provided for dates fromNow you write your custom relative time for moment.

    For example, in my own case I wanted to print 'one month ago' instead of 'a month ago' (provided by moment(d).fromNow()). In this case, you can write something given below.

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

    NOTE: I wrote my code for project in Angular 6

提交回复
热议问题