Files
sam-react-prod/src/lib/utils/date.ts

84 lines
2.5 KiB
TypeScript
Raw Normal View History

/**
*
*/
/**
* 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);
}
/**
* (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}`;
}