Skip to content

Instantly share code, notes, and snippets.

@pomber
Created February 14, 2020 17:22
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pomber/6195066a9258d1fb93bb59c206345b38 to your computer and use it in GitHub Desktop.
Save pomber/6195066a9258d1fb93bb59c206345b38 to your computer and use it in GitHub Desktop.
Get a time ago human friendly string from a date (like dates in twitter).
const MINUTE = 60,
HOUR = MINUTE * 60,
DAY = HOUR * 24,
YEAR = DAY * 365;
function getTimeAgo(date) {
const secondsAgo = Math.round((+new Date() - date) / 1000);
if (secondsAgo < MINUTE) {
return secondsAgo + "s";
} else if (secondsAgo < HOUR) {
return Math.floor(secondsAgo / MINUTE) + "m";
} else if (secondsAgo < DAY) {
return Math.floor(secondsAgo / HOUR) + "h";
} else if (secondsAgo < YEAR) {
return date.toLocaleString("default", { day: "numeric", month: "short" });
} else {
return date.toLocaleString("default", { year: "numeric", month: "short" });
}
}
@JeremyBernier
Copy link

JeremyBernier commented Jul 13, 2022

Problem is it'll return "1 seconds ago". Here's my modified version:

const MINUTE = 60;
const HOUR = MINUTE * 60;
const DAY = HOUR * 24;
const WEEK = DAY * 7;
const MONTH = DAY * 30;
const YEAR = DAY * 365;

function getTimeAgo(date) {
  const secondsAgo = Math.round((Date.now() - Number(date)) / 1000);

  if (secondsAgo < MINUTE) {
    return secondsAgo + ` second${secondsAgo !== 1 ? "s" : ""} ago`;
  }

  let divisor;
  let unit = "";

  if (secondsAgo < HOUR) {
    [divisor, unit] = [MINUTE, "minute"];
  } else if (secondsAgo < DAY) {
    [divisor, unit] = [HOUR, "hour"];
  } else if (secondsAgo < WEEK) {
    [divisor, unit] = [DAY, "day"];
  } else if (secondsAgo < MONTH) {
    [divisor, unit] = [WEEK, "week"];
  } else if (secondsAgo < YEAR) {
    [divisor, unit] = [MONTH, "month"];
  } else {
    [divisor, unit] = [YEAR, "year"];
  }

  const count = Math.floor(secondsAgo / divisor);
  return `${count} ${unit}${count > 1 ? "s" : ""} ago`;
}

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