studiocms
Version:
Astro Native CMS for AstroDB. Built from the ground up by the Astro community.
22 lines (21 loc) • 729 B
JavaScript
function timeAgo(date) {
const now = /* @__PURE__ */ new Date();
const past = new Date(date);
const diffInMs = now.getTime() - past.getTime();
if (Number.isNaN(diffInMs)) {
return "Invalid date";
}
const minutes = Math.floor(diffInMs / (1e3 * 60)) % 60;
const hours = Math.floor(diffInMs / (1e3 * 60 * 60)) % 24;
const days = Math.floor(diffInMs / (1e3 * 60 * 60 * 24));
const parts = [];
if (days > 0) parts.push(`${days} day${days > 1 ? "s" : ""}`);
if (days === 0) {
if (hours > 0) parts.push(`${hours} hour${hours > 1 ? "s" : ""}`);
if (minutes > 0 || parts.length === 0) parts.push(`${minutes} min${minutes > 1 ? "s" : ""}`);
}
return `${parts.join(", ")} ago`;
}
export {
timeAgo
};