relativeSince.ts 997 Bytes
/** 解析后端常见时间串(含 `yyyy-MM-dd HH:mm:ss`) */
function parseBackendDate(iso: string | null | undefined): Date | null {
  if (iso == null) return null;
  const s = String(iso).trim();
  if (!s) return null;
  let d = new Date(s);
  if (Number.isFinite(d.getTime())) return d;
  const normalized = s.includes('T') ? s : s.replace(' ', 'T');
  d = new Date(normalized);
  return Number.isFinite(d.getTime()) ? d : null;
}

/** 相对「多久以前」:用于会话 `lastUpdated`、打印时间等 */
export function formatRelativeSince(iso: string | null | undefined): string {
  const parsed = parseBackendDate(iso);
  if (!parsed) return '—';
  const t = parsed.getTime();
  const diffSec = Math.max(0, Math.round((Date.now() - t) / 1000));
  if (diffSec < 60) return 'Just now';
  if (diffSec < 3600) return `${Math.floor(diffSec / 60)} min ago`;
  if (diffSec < 86400) return `${Math.floor(diffSec / 3600)} hr ago`;
  return `${Math.floor(diffSec / 86400)} day(s) ago`;
}