import type { PausePeriod } from "./types.ts"; export function activeDurationMs(startedAt?: number, finishedAt?: number, pausePeriods: PausePeriod[] = [], now = Date.now()): number { if (startedAt === undefined) return 0; const endedAt = finishedAt ?? now; const pausedMs = pausePeriods.reduce((total, period) => { const overlapStartedAt = Math.max(startedAt, period.startedAt); const overlapFinishedAt = Math.min(endedAt, period.finishedAt ?? now); return total + Math.max(0, overlapFinishedAt - overlapStartedAt); }, 0); return Math.max(0, endedAt - startedAt - pausedMs); } export function formatDuration(startedAt?: number, finishedAt?: number, pausePeriods: PausePeriod[] = [], now = Date.now()): string { if (startedAt === undefined) return "未开始"; const elapsedSeconds = Math.floor(activeDurationMs(startedAt, finishedAt, pausePeriods, now) / 1000); const seconds = elapsedSeconds % 60; const minutes = Math.floor(elapsedSeconds / 60) % 60; const hours = Math.floor(elapsedSeconds / 3_600) % 24; const days = Math.floor(elapsedSeconds / 86_400); const pad = (value: number) => String(value).padStart(2, "0"); if (days > 0) return `${days}天${pad(hours)}小时${pad(minutes)}分${pad(seconds)}秒`; if (hours > 0) return `${hours}小时${pad(minutes)}分${pad(seconds)}秒`; if (minutes > 0) return `${minutes}分${pad(seconds)}秒`; return `${seconds}秒`; }