Files
message-inbox-web-frontend-sdk/apps/web/lib/format.ts
T
2026-07-17 21:48:37 +05:30

41 lines
1.3 KiB
TypeScript

export function relativeTime(ts: number): string {
const diff = Date.now() - ts;
const s = Math.round(diff / 1000);
if (s < 45) return "just now";
const m = Math.round(s / 60);
if (m < 60) return `${m}m`;
const h = Math.round(m / 60);
if (h < 24) return `${h}h`;
const d = Math.round(h / 24);
if (d < 7) return `${d}d`;
return new Date(ts).toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
export function clockTime(ts: number): string {
return new Date(ts).toLocaleTimeString(undefined, {
hour: "numeric",
minute: "2-digit",
});
}
export function dayLabel(ts: number): string {
const d = new Date(ts);
const today = new Date();
const yst = new Date();
yst.setDate(today.getDate() - 1);
if (d.toDateString() === today.toDateString()) return "Today";
if (d.toDateString() === yst.toDateString()) return "Yesterday";
return d.toLocaleDateString(undefined, { weekday: "long", month: "long", day: "numeric" });
}
export function groupByDay<T extends { ts: number }>(items: T[]): { day: string; items: T[] }[] {
const out: { day: string; items: T[] }[] = [];
for (const it of items) {
const label = dayLabel(it.ts);
const last = out[out.length - 1];
if (last && last.day === label) last.items.push(it);
else out.push({ day: label, items: [it] });
}
return out;
}