format.ts 2.33 KB
/** 展示层格式化。统一出口,避免各面板自己写一套导致同一数值在页面上出现两种写法 */

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;
}