How to format time since xxx e.g. “4 minutes ago”

2019-01-01 01:37发布

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.

  • 1 minute ago
  • 1 hour ago
  • 1 day ago
  • 1 month ago
  • 1 year ago

19条回答
像晚风撩人
2楼-- · 2019-01-01 01:54

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'));

查看更多
其实,你不懂
3楼-- · 2019-01-01 01:55

An ES6 version of the code provided by @user1012181

// Epochs
const epochs = [
    ['year', 31536000],
    ['month', 2592000],
    ['day', 86400],
    ['hour', 3600],
    ['minute', 60],
    ['second', 1]
];


// Get duration
const getDuration = (timeAgoInSeconds) => {
    for (let [name, seconds] of epochs) {
        const interval = Math.floor(timeAgoInSeconds / seconds);

        if (interval >= 1) {
            return {
                interval: interval,
                epoch: name
            };
        }
    }
};


// Calculate
const timeAgo = (date) => {
    const timeAgoInSeconds = Math.floor((new Date() - new Date(date)) / 1000);
    const {interval, epoch} = getDuration(timeAgoInSeconds);
    const suffix = interval === 1 ? '' : 's';

    return `${interval} ${epoch}${suffix} ago`;
};

Edited with @ibe-vanmeenen suggestions. (Thanks !)

查看更多
ら面具成の殇う
4楼-- · 2019-01-01 01:56

Simple and readable version:

const NOW = new Date()
const times = [["second", 1], ["minute", 60], ["hour", 3600], ["day", 86400], ["week", 604800], ["month", 2592000], ["year", 31536000]]

function timeAgo(date) {
    var diff = Math.round((NOW - date) / 1000)
    for (var t = 0; t < times.length; t++) {
        if (diff < times[t][1]) {
            if (t == 0) {
                return "Just now"
            } else {
                diff = Math.round(diff / times[t - 1][1])
                return diff + " " + times[t - 1][0] + (diff == 1?" ago":"s ago")
            }
        }
    }
}
查看更多
大哥的爱人
5楼-- · 2019-01-01 02:00

function timeSince(date) {

  var seconds = Math.floor((new Date() - date) / 1000);

  var interval = Math.floor(seconds / 31536000);

  if (interval > 1) {
    return interval + " years";
  }
  interval = Math.floor(seconds / 2592000);
  if (interval > 1) {
    return interval + " months";
  }
  interval = Math.floor(seconds / 86400);
  if (interval > 1) {
    return interval + " days";
  }
  interval = Math.floor(seconds / 3600);
  if (interval > 1) {
    return interval + " hours";
  }
  interval = Math.floor(seconds / 60);
  if (interval > 1) {
    return 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)));

查看更多
与君花间醉酒
6楼-- · 2019-01-01 02:00

I write one with js and python, used in two projects, very nice and simple: a simple library (less then 2kb) used to format date with *** time ago statement.

simple, small, easy used, and well tested.

  1. npm install timeago.js

  2. import timeago from 'timeago.js'; // or use script tag

  3. use api format.

Sample:

var timeagoIns  = timeago();
timeagoIns .format('2016-06-12');

Also you can render in real-time.

var timeagoIns = timeago();
timeagoIns.render(document.querySelectorAll('time'));
查看更多
深知你不懂我心
7楼-- · 2019-01-01 02:01

I haven't checked (although it wouldn't be hard to), but I think that Stack Exchange sites use the jquery.timeago plugin to create these time strings.


It's quite easy to use the plugin, and it's clean and updates automatically.

Here's a quick sample (from the plugin's home page):

First, load jQuery and the plugin:

<script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.timeago.js" type="text/javascript"></script>

Now, let's attach it to your timestamps on DOM ready:

jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago(); });

This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title: <abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr> into something like this: <abbr class="timeago" title="July 17, 2008">about a year ago</abbr> which yields: about a year ago. As time passes, the timestamps will automatically update.

查看更多
登录 后发表回答