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

后端 未结 25 1910
遥遥无期
遥遥无期 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条回答
  •  旧时难觅i
    2020-11-22 13:20

    Changed the function above to

    function timeSince(date) {
    
        var seconds = Math.floor(((new Date().getTime()/1000) - date)),
        interval = Math.floor(seconds / 31536000);
    
        if (interval > 1) return interval + "y";
    
        interval = Math.floor(seconds / 2592000);
        if (interval > 1) return interval + "m";
    
        interval = Math.floor(seconds / 86400);
        if (interval >= 1) return interval + "d";
    
        interval = Math.floor(seconds / 3600);
        if (interval >= 1) return interval + "h";
    
        interval = Math.floor(seconds / 60);
        if (interval > 1) return interval + "m ";
    
        return Math.floor(seconds) + "s";
    }
    

    Otherwise it would show things like "75 minutes" (between 1 and 2 hours). It also now assumes input date is a Unix timestamp.

提交回复
热议问题