/** * 请假:日期时间解析、按天/按小时时长计算。 */ import { LEAVE_TYPE_BY_DAY } from '../constants/leave'; export function formatDateTime(date: Date): string { const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const hours = String(date.getHours()).padStart(2, '0'); const minutes = String(date.getMinutes()).padStart(2, '0'); return `${year}-${month}-${day}T${hours}:${minutes}`; } export function parseDateTime(value: string): Date | null { const normalized = (value || '').trim().replace('T', ' '); const match = normalized.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/); if (!match) return null; const [, year, month, day, hour, minute] = match; const date = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute)); return Number.isNaN(date.getTime()) ? null : date; } export function isLeaveTypeByDay(leaveType: string): boolean { return LEAVE_TYPE_BY_DAY.has(leaveType); } export function calculateDurationHours(startTime: string, endTime: string): number { const start = parseDateTime(startTime); const end = parseDateTime(endTime); if (!start || !end || end.getTime() <= start.getTime()) return 0; return Number((((end.getTime() - start.getTime()) / 1000 / 60 / 60)).toFixed(2)); } export function syncLeaveDuration(form: { leaveType: string; startTime: string; endTime: string; durationHours: number }) { if (isLeaveTypeByDay(form.leaveType)) { const start = parseDateTime(form.startTime); const end = parseDateTime(form.endTime); if (!start || !end || end.getTime() <= start.getTime()) { form.durationHours = 0; return; } const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate()); const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate()); const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1); form.durationHours = days * 8; } else { form.durationHours = calculateDurationHours(form.startTime, form.endTime); } }