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

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

    function dateToHowManyAgo(stringDate){
        var currDate = new Date();
        var diffMs=currDate.getTime() - new Date(stringDate).getTime();
        var sec=diffMs/1000;
        if(sec<60)
            return parseInt(sec)+' second'+(parseInt(sec)>1?'s':'')+' ago';
        var min=sec/60;
        if(min<60)
            return parseInt(min)+' minute'+(parseInt(min)>1?'s':'')+' ago';
        var h=min/60;
        if(h<24)
            return parseInt(h)+' hour'+(parseInt(h)>1?'s':'')+' ago';
        var d=h/24;
        if(d<30)
            return parseInt(d)+' day'+(parseInt(d)>1?'s':'')+' ago';
        var m=d/30;
        if(m<12)
            return parseInt(m)+' month'+(parseInt(m)>1?'s':'')+' ago';
        var y=m/12;
        return parseInt(y)+' year'+(parseInt(y)>1?'s':'')+' ago';
    }
    console.log(dateToHowManyAgo('2019-11-07 19:17:06'));
    

提交回复
热议问题