/** * 날짜 관련 유틸리티 함수 */ /** * 로컬 시간대 기준 YYYY-MM-DD 형식 반환 * * 주의: toISOString()은 UTC 기준이므로 한국 시간대(UTC+9)에서 * 오전 9시 이전에 사용하면 하루 전 날짜가 반환됨 * * @example * // 2025-01-26 08:30 KST * new Date().toISOString().split('T')[0] // "2025-01-25" (잘못됨) * getLocalDateString(new Date()) // "2025-01-26" (정확함) */ export function getLocalDateString(date: Date = new Date()): string { 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}`; } /** * 오늘 날짜를 YYYY-MM-DD 형식으로 반환 (로컬 시간대 기준) */ export function getTodayString(): string { return getLocalDateString(new Date()); } /** * N일 후 날짜를 YYYY-MM-DD 형식으로 반환 (로컬 시간대 기준) */ export function getDateAfterDays(days: number): string { const date = new Date(); date.setDate(date.getDate() + days); return getLocalDateString(date); } /** * API 날짜 문자열을 HTML date input용 YYYY-MM-DD 형식으로 변환 * 지원 형식: ISO 8601, datetime string, date only */ export function formatDateForInput(dateStr: string | null | undefined): string { if (!dateStr) return ''; // 이미 YYYY-MM-DD 형식인 경우 if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) { return dateStr; } // ISO 8601 또는 datetime 형식 (2025-01-06T00:00:00.000Z, 2025-01-06 00:00:00) const date = new Date(dateStr); if (isNaN(date.getTime())) { return ''; // 유효하지 않은 날짜 } // 로컬 시간대 기준 YYYY-MM-DD 형식으로 변환 return getLocalDateString(date); } /** * ISO 문자열에서 날짜 부분(YYYY-MM-DD)만 추출 * null/undefined 시 빈 문자열 반환 (폼 데이터 변환용) * @example toDateString("2025-01-06T00:00:00.000Z") // "2025-01-06" * @example toDateString(null) // "" */ export function toDateString(isoString: string | null | undefined): string { if (!isoString) return ''; return isoString.split('T')[0]; } /** * 날짜 표시용 포맷 (YYYY-MM-DD) * @example formatDate("2025-01-06T00:00:00.000Z") // "2025-01-06" * @example formatDate(null) // "-" */ export function formatDate(dateStr: string | null | undefined): string { if (!dateStr) return '-'; // ISO string에서 날짜 부분만 추출, 또는 이미 YYYY-MM-DD면 그대로 return dateStr.split('T')[0]; } /** * 날짜 범위 포맷 ("시작 ~ 종료") * @example formatDateRange("2025-01-01", "2025-12-31") // "2025-01-01 ~ 2025-12-31" */ export function formatDateRange( startDate: string | null | undefined, endDate: string | null | undefined ): string { const start = formatDate(startDate); const end = formatDate(endDate); if (start === '-' && end === '-') return '-'; return `${start} ~ ${end}`; }