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

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

    Much readable and cross browser compatible code:

    As given by @Travis

    var DURATION_IN_SECONDS = {
      epochs: ['year', 'month', 'day', 'hour', 'minute'],
      year: 31536000,
      month: 2592000,
      day: 86400,
      hour: 3600,
      minute: 60
    };
    
    function getDuration(seconds) {
      var epoch, interval;
    
      for (var i = 0; i < DURATION_IN_SECONDS.epochs.length; i++) {
        epoch = DURATION_IN_SECONDS.epochs[i];
        interval = Math.floor(seconds / DURATION_IN_SECONDS[epoch]);
        if (interval >= 1) {
          return {
            interval: interval,
            epoch: epoch
          };
        }
      }
    
    };
    
    function timeSince(date) {
      var seconds = Math.floor((new Date() - new Date(date)) / 1000);
      var duration = getDuration(seconds);
      var suffix = (duration.interval > 1 || duration.interval === 0) ? 's' : '';
      return duration.interval + ' ' + duration.epoch + suffix;
    };
    
    alert(timeSince('2015-09-17T18:53:23'));

提交回复
热议问题