import { format } from 'date-fns'; export const formatMemory = (bytes: number | string) => { bytes = typeof bytes === 'string' ? parseInt(bytes, 10) : bytes; const units = ['B', 'KB', 'MB', 'GB']; let size = bytes; let unitIndex = 0; while (size >= 1024 && unitIndex < units.length - 1) { size /= 1024; unitIndex++; } return `${size.toFixed(1)} ${units[unitIndex]}`; }; export const formatDate = (date: string | Date, type: 'full' | 'short' = 'full') => { if (type === 'short') { return format(new Date(date), 'MM-dd HH:mm'); } return format(new Date(date), 'yyyy-MM-dd HH:mm:ss'); }; export const formatDuration = (durationSeconds: number) => { if (durationSeconds <= 0) return '0分钟'; const hours = Math.floor(durationSeconds / 3600); const minutes = Math.floor((durationSeconds % 3600) / 60); const seconds = durationSeconds % 60; if (hours > 0) { if (minutes > 0) { return `${hours}小时 ${minutes}分钟`; } return `${hours}小时`; } if (minutes > 0) { if (seconds > 0 && minutes < 5) { return `${minutes}分钟 ${seconds}秒`; } return `${minutes}分钟`; } return `${seconds}秒`; }; export const getLocalDateInputValue = (date = new Date()) => { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; }; export const shiftDateInputValue = (dateString: string, amount: number) => { const [year, month, day] = dateString.split('-').map(Number); const next = new Date(year, month - 1, day); next.setDate(next.getDate() + amount); return getLocalDateInputValue(next); }; export const formatScreenTimePeriod = (startDate: string, endDate: string, unit: 'day' | 'week') => { if (unit === 'day') { return startDate; } if (startDate === endDate) { return startDate; } return `${startDate} 至 ${endDate}`; };