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

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

    function timeago(date) {
        var seconds = Math.floor((new Date() - date) / 1000);
        if(Math.round(seconds/(60*60*24*365.25)) >= 2) return Math.round(seconds/(60*60*24*365.25)) + " years ago";
        else if(Math.round(seconds/(60*60*24*365.25)) >= 1) return "1 year ago";
        else if(Math.round(seconds/(60*60*24*30.4)) >= 2) return Math.round(seconds/(60*60*24*30.4)) + " months ago";
        else if(Math.round(seconds/(60*60*24*30.4)) >= 1) return "1 month ago";
        else if(Math.round(seconds/(60*60*24*7)) >= 2) return Math.round(seconds/(60*60*24*7)) + " weeks ago";
        else if(Math.round(seconds/(60*60*24*7)) >= 1) return "1 week ago";
        else if(Math.round(seconds/(60*60*24)) >= 2) return Math.round(seconds/(60*60*24)) + " days ago";
        else if(Math.round(seconds/(60*60*24)) >= 1) return "1 day ago";
        else if(Math.round(seconds/(60*60)) >= 2) return Math.round(seconds/(60*60)) + " hours ago";
        else if(Math.round(seconds/(60*60)) >= 1) return "1 hour ago";
        else if(Math.round(seconds/60) >= 2) return Math.round(seconds/60) + " minutes ago";
        else if(Math.round(seconds/60) >= 1) return "1 minute ago";
        else if(seconds >= 2)return seconds + " seconds ago";
        else return seconds + "1 second ago";
    }
    

提交回复
热议问题