Blame view

美国版/Food Labeling Management Platform/src/lib/relativeSince.ts 997 Bytes
ef6b3255   杨鑫   修改BUG
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  /** 解析后端常见时间串(含 `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`;
  }