Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active February 27, 2023 04:03
Show Gist options
  • Select an option

  • Save lewdev/f51284b4960db029c3b90a2bb76f1c41 to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/f51284b4960db029c3b90a2bb76f1c41 to your computer and use it in GitHub Desktop.
πŸ“… Date Distance JavaScript function (i.e. "3mo ago", "5d until")
<pre id=o></pre>
<script>
const TIME = [1e3, "s", 6e4, "min", 36e5, "hr", 864e5, "d", 2592e6, "wk", 2592e6, "mo", 31536e6, "yr"];
const dateDistance = dateStr => {
const now = new Date().getTime();
let diff = now - new Date(dateStr).getTime();
let agoOrUntil = " ago";
if (diff < 0) { agoOrUntil = " until"; diff = Math.abs(diff); }
for (let i = 12; i >= 0; i-=2) {
const t = TIME[i];
if (diff >= t) return ~~(diff / t) + TIME[i + 1] + agoOrUntil;
}
return diff + "ms" + agoOrUntil;
};
o.innerHTML = dateDistance("2023-02-27T04:01:00.497Z");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment