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

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

    function timeSince(date) {
    
      var seconds = Math.floor((new Date() - date) / 1000);
    
      var interval = seconds / 31536000;
    
      if (interval > 1) {
        return Math.floor(interval) + " years";
      }
      interval = seconds / 2592000;
      if (interval > 1) {
        return Math.floor(interval) + " months";
      }
      interval = seconds / 86400;
      if (interval > 1) {
        return Math.floor(interval) + " days";
      }
      interval = seconds / 3600;
      if (interval > 1) {
        return Math.floor(interval) + " hours";
      }
      interval = seconds / 60;
      if (interval > 1) {
        return Math.floor(interval) + " minutes";
      }
      return Math.floor(seconds) + " seconds";
    }
    var aDay = 24*60*60*1000;
    console.log(timeSince(new Date(Date.now()-aDay)));
    console.log(timeSince(new Date(Date.now()-aDay*2)));

提交回复
热议问题