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

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

    Here is a slight modification on Sky Sander's solution that allows the date to be input as a string and is capable of displaying spans like "1 minute" instead of "73 seconds"

    var timeSince = function(date) {
      if (typeof date !== 'object') {
        date = new Date(date);
      }
    
      var seconds = Math.floor((new Date() - date) / 1000);
      var intervalType;
    
      var interval = Math.floor(seconds / 31536000);
      if (interval >= 1) {
        intervalType = 'year';
      } else {
        interval = Math.floor(seconds / 2592000);
        if (interval >= 1) {
          intervalType = 'month';
        } else {
          interval = Math.floor(seconds / 86400);
          if (interval >= 1) {
            intervalType = 'day';
          } else {
            interval = Math.floor(seconds / 3600);
            if (interval >= 1) {
              intervalType = "hour";
            } else {
              interval = Math.floor(seconds / 60);
              if (interval >= 1) {
                intervalType = "minute";
              } else {
                interval = seconds;
                intervalType = "second";
              }
            }
          }
        }
      }
    
      if (interval > 1 || interval === 0) {
        intervalType += 's';
      }
    
      return interval + ' ' + intervalType;
    };
    var aDay = 24 * 60 * 60 * 1000;
    console.log(timeSince(new Date(Date.now() - aDay)));
    console.log(timeSince(new Date(Date.now() - aDay * 2)));

提交回复
热议问题