sing-ui/components/format.ts

33 lines
986 B
TypeScript

// SQLite datetime('now') 存的是 UTC "YYYY-MM-DD HH:MM:SS",直接 new Date 会被当作本地时间。
function toDate(s: string): Date {
const iso = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?$/.test(s)
? s.replace(" ", "T") + "Z"
: s;
return new Date(iso);
}
export function fmtTime(s: string | null | undefined): string {
if (!s) return "-";
const d = toDate(s);
return isNaN(d.getTime()) ? s : d.toLocaleString();
}
export function fmtDuration(
start: string | null | undefined,
end: string | null | undefined
): string {
if (!start) return "-";
const a = toDate(start).getTime();
if (isNaN(a)) return "-";
const b = end ? toDate(end).getTime() : Date.now();
if (isNaN(b)) return "-";
let sec = Math.max(0, Math.round((b - a) / 1000));
const h = Math.floor(sec / 3600);
sec -= h * 3600;
const m = Math.floor(sec / 60);
sec -= m * 60;
if (h > 0) return `${h}h ${m}m ${sec}s`;
if (m > 0) return `${m}m ${sec}s`;
return `${sec}s`;
}