pingql/apps/shared/render/time.ts

14 lines
633 B
TypeScript

// Server-rendered "X ago" timestamp. Returns an HTML span carrying the original
// epoch ms in a data attribute so a tiny client script can refresh it without a
// re-render. Reused by the dashboard and the public status pages.
export function timeAgoSSR(date: string | Date): string {
const ts = new Date(date).getTime();
const s = Math.ceil((Date.now() - ts) / 1000) || 1;
const text =
s < 60 ? `${s}s ago`
: s < 3600 ? `${Math.floor(s / 60)}m ago`
: s < 86400 ? `${Math.floor(s / 3600)}h ago`
: `${Math.floor(s / 86400)}d ago`;
return `<span class="timestamp" data-ts="${ts}">${text}</span>`;
}