Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Last active January 25, 2023 17:05
Show Gist options
  • Save codeincontext/1285806 to your computer and use it in GitHub Desktop.
Save codeincontext/1285806 to your computer and use it in GitHub Desktop.
Javascript function to show how long ago a timestamp was as a pretty string
function timeAgo(time){
var units = [
{ name: "second", limit: 60, in_seconds: 1 },
{ name: "minute", limit: 3600, in_seconds: 60 },
{ name: "hour", limit: 86400, in_seconds: 3600 },
{ name: "day", limit: 604800, in_seconds: 86400 },
{ name: "week", limit: 2629743, in_seconds: 604800 },
{ name: "month", limit: 31556926, in_seconds: 2629743 },
{ name: "year", limit: null, in_seconds: 31556926 }
];
var diff = (new Date() - new Date(time*1000)) / 1000;
if (diff < 5) return "now";
var i = 0, unit;
while (unit = units[i++]) {
if (diff < unit.limit || !unit.limit){
var diff = Math.floor(diff / unit.in_seconds);
return diff + " " + unit.name + (diff>1 ? "s" : "");
}
};
}
@jcary741
Copy link

jcary741 commented Jan 25, 2023

Here's an updated version for ES6 :)

/**
 * Returns a human-friendly "time ago" string for the given date, and switches to Locale Date String if date is older than 4 days ago.
 * Examples:
 * - a few moments ago
 * - 50 seconds ago
 * - 1 minute ago
 * - 2 hours ago
 * - 3 days ago
 * - {locale date string}
 *
 * @param timestamp {Date|string}
 * @returns {string}
 */
export function timeAgo(timestamp) {
  if (!timestamp) {
    return '';
  }
  if (typeof timestamp === 'string') {
    timestamp = new Date(timestamp);
  }
  const units = [
    {name: "second", limit: 60, in_seconds: 1},
    {name: "minute", limit: 3600, in_seconds: 60},
    {name: "hour", limit: 86400, in_seconds: 3600},
    {name: "day", limit: 345600, in_seconds: 86400}
  ];
  let diff = (new Date().getTime() - timestamp.getTime()) / 1000;
  if (diff < 5) return "a few moments ago";
  let _ago;
  for (const unit of units) {
    if (diff < unit.limit){
      diff = Math.floor(diff / unit.in_seconds);
      _ago = diff + " " + unit.name + (diff>1 ? "s" : "");
      break;
    }
  }
  if (_ago) {
    return _ago + ' ago';
  } else {
    return timestamp.toLocaleDateString();
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment