Skip to content

Instantly share code, notes, and snippets.

@Legend-of-iPhoenix
Last active October 14, 2020 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Legend-of-iPhoenix/c022975710503144c6d02e9f5c82d592 to your computer and use it in GitHub Desktop.
Save Legend-of-iPhoenix/c022975710503144c6d02e9f5c82d592 to your computer and use it in GitHub Desktop.
// formats a duration as a human readable string, ex. "5 days, 4 minutes, and 1 second ago".
function formatDuration(ms) {
let parts = [];
const addPart = (value, maxValue, label) => {
value = Math.floor(value) % maxValue;
if (value > 0) {
parts.unshift(value + " " + label + (value === 1 ? "" : "s"));
}
}
const seconds = ms / 1000;
addPart(seconds, 60, "second");
const minutes = seconds / 60;
addPart(minutes, 60, "minute");
const hours = minutes / 60;
addPart(hours, 24, "hour");
const days = hours / 24;
addPart(days, Infinity, "day");
let result = "";
switch (parts.length) {
case 0: {
return "now";
};
case 1:
case 2: {
return parts.join(" and ") + " ago";
};
default: {
parts.push("and " + parts.pop());
return parts.join(", ") + " ago";
}
}
}
// reuse allowed with attribution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment