short-time-ago
Version:
A small, no dependencies, Typescript utility to describe time differences in a human readable format (for example, '1 minute ago')
26 lines (25 loc) • 698 B
JavaScript
// src/index.ts
function timeAgo(date, now) {
const units = [
["year", 365 * 24 * 60 * 60 * 1e3],
["month", 30.5 * 24 * 60 * 60 * 1e3],
["day", 24 * 60 * 60 * 1e3],
["hour", 60 * 60 * 1e3],
["minute", 60 * 1e3],
["second", 1e3]
];
const diff = (now || /* @__PURE__ */ new Date()).getTime() - date.getTime();
const elapsed = Math.abs(diff);
for (const [name, size] of units) {
const value = Math.floor(elapsed / size);
if (value > 0) {
const plural = value > 1 ? "s" : "";
const description = `${value} ${name}${plural}`;
return diff > 0 ? `${description} ago` : `in ${description}`;
}
}
return "just now";
}
export {
timeAgo
};