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

后端 未结 25 1625
遥遥无期
遥遥无期 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:29

    My stab at this based on other answers.

    function timeSince(date) {
        let minute = 60;
        let hour   = minute * 60;
        let day    = hour   * 24;
        let month  = day    * 30;
        let year   = day    * 365;
    
        let suffix = ' ago';
    
        let elapsed = Math.floor((Date.now() - date) / 1000);
    
        if (elapsed < minute) {
            return 'just now';
        }
    
        // get an array in the form of [number, string]
        let a = elapsed < hour  && [Math.floor(elapsed / minute), 'minute'] ||
                elapsed < day   && [Math.floor(elapsed / hour), 'hour']     ||
                elapsed < month && [Math.floor(elapsed / day), 'day']       ||
                elapsed < year  && [Math.floor(elapsed / month), 'month']   ||
                [Math.floor(elapsed / year), 'year'];
    
        // pluralise and append suffix
        return a[0] + ' ' + a[1] + (a[0] === 1 ? '' : 's') + suffix;
    }
    

提交回复
热议问题