format.ts
2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/** 展示层格式化。统一出口,避免各面板自己写一套导致同一数值在页面上出现两种写法 */
const DAY = 86400;
function pad(v: number): string {
return String(v).padStart(2, '0');
}
/** epoch 秒 → 北京时间 YYYY-MM-DD */
export function fmtDate(sec: number | null | undefined): string {
if (!sec) return '—';
const d = new Date(sec * 1000 + 8 * 3600 * 1000);
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
}
/** epoch 秒 → 北京时间 YYYY-MM-DD HH:mm */
export function fmtDateTime(sec: number | null | undefined): string {
if (!sec) return '—';
const d = new Date(sec * 1000 + 8 * 3600 * 1000);
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;
}
/** 相对天数描述,用于「数据覆盖近 N 天」这类说明 */
export function spanDays(from: number, to: number): number {
return Math.max(0, Math.round((to - from) / DAY) + 1);
}
export function fmtInt(n: number): string {
return n.toLocaleString('zh-CN');
}
/** 大数压缩:图上数字与指标块共用同一套压缩规则,避免同页出现 12,345 与 1.2万 两种写法 */
export function fmtCompact(n: number): string {
if (n >= 100000000) return `${(n / 100000000).toFixed(2)}亿`;
if (n >= 10000) return `${(n / 10000).toFixed(1)}万`;
return fmtInt(n);
}
export function fmtPercent(part: number, total: number): string {
if (!total) return '0%';
return `${((part / total) * 100).toFixed(1)}%`;
}
export function fmtMs(ms: number): string {
if (ms >= 1000) return `${(ms / 1000).toFixed(2)}s`;
return `${ms.toFixed(ms >= 10 ? 0 : 1)}ms`;
}
export function fmtBytes(bytes: number): string {
if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
return `${bytes} B`;
}
/** 街道字典项 "福田区|华强北街道" → 街道名 */
export function streetNameOf(dictItem: string | undefined): string {
if (!dictItem) return '—';
const i = dictItem.indexOf('|');
return i >= 0 ? dictItem.slice(i + 1) : dictItem;
}
export function districtNameOf(dictItem: string | undefined): string {
if (!dictItem) return '—';
const i = dictItem.indexOf('|');
return i >= 0 ? dictItem.slice(0, i) : dictItem;
}