20 lines
765 B
TypeScript
20 lines
765 B
TypeScript
/**
|
|
* Compact relative time ("just now", "5m ago", "3h ago", "2d ago"), falling
|
|
* back to a locale date for anything older than a week. Shared across the
|
|
* notification feed, the comments drawer, and anywhere else that shows a
|
|
* timestamp tail.
|
|
*/
|
|
export function timeAgo(iso: string): string {
|
|
const then = new Date(iso).getTime();
|
|
if (Number.isNaN(then)) return "";
|
|
const secs = Math.max(0, Math.floor((Date.now() - then) / 1000));
|
|
if (secs < 45) return "just now";
|
|
const mins = Math.floor(secs / 60);
|
|
if (mins < 60) return `${mins}m ago`;
|
|
const hours = Math.floor(mins / 60);
|
|
if (hours < 24) return `${hours}h ago`;
|
|
const days = Math.floor(hours / 24);
|
|
if (days < 7) return `${days}d ago`;
|
|
return new Date(iso).toLocaleDateString();
|
|
}
|