61 lines
1.9 KiB
TypeScript
61 lines
1.9 KiB
TypeScript
|
|
'use client';
|
||
|
|
|
||
|
|
import { useState } from 'react';
|
||
|
|
import { getLocalDateString } from '@/lib/utils/date';
|
||
|
|
|
||
|
|
// ===== 프리셋 타입 =====
|
||
|
|
export type DateRangePreset = 'currentYear' | 'currentMonth' | 'today' | 'none';
|
||
|
|
|
||
|
|
// ===== 반환 타입 =====
|
||
|
|
export interface UseDateRangeReturn {
|
||
|
|
startDate: string;
|
||
|
|
endDate: string;
|
||
|
|
setStartDate: React.Dispatch<React.SetStateAction<string>>;
|
||
|
|
setEndDate: React.Dispatch<React.SetStateAction<string>>;
|
||
|
|
}
|
||
|
|
|
||
|
|
// ===== 프리셋별 초기값 계산 =====
|
||
|
|
function getInitialDates(preset: DateRangePreset): { start: string; end: string } {
|
||
|
|
const now = new Date();
|
||
|
|
switch (preset) {
|
||
|
|
case 'currentYear': {
|
||
|
|
const year = now.getFullYear();
|
||
|
|
return { start: `${year}-01-01`, end: `${year}-12-31` };
|
||
|
|
}
|
||
|
|
case 'currentMonth': {
|
||
|
|
const year = now.getFullYear();
|
||
|
|
const month = String(now.getMonth() + 1).padStart(2, '0');
|
||
|
|
const lastDay = new Date(year, now.getMonth() + 1, 0).getDate();
|
||
|
|
return {
|
||
|
|
start: `${year}-${month}-01`,
|
||
|
|
end: `${year}-${month}-${String(lastDay).padStart(2, '0')}`,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
case 'today': {
|
||
|
|
const today = getLocalDateString(now);
|
||
|
|
return { start: today, end: today };
|
||
|
|
}
|
||
|
|
case 'none':
|
||
|
|
return { start: '', end: '' };
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 날짜 범위 상태 관리 훅
|
||
|
|
*
|
||
|
|
* @param preset - 초기 날짜 범위 프리셋
|
||
|
|
* - 'currentYear': 올해 1/1 ~ 12/31 (회계 관리 기본값)
|
||
|
|
* - 'currentMonth': 이번 달 1일 ~ 말일
|
||
|
|
* - 'today': 오늘 ~ 오늘 (로컬 시간대 기준)
|
||
|
|
* - 'none': 빈 문자열
|
||
|
|
*
|
||
|
|
* @example
|
||
|
|
* const { startDate, endDate, setStartDate, setEndDate } = useDateRange('currentYear');
|
||
|
|
*/
|
||
|
|
export function useDateRange(preset: DateRangePreset = 'currentYear'): UseDateRangeReturn {
|
||
|
|
const [startDate, setStartDate] = useState(() => getInitialDates(preset).start);
|
||
|
|
const [endDate, setEndDate] = useState(() => getInitialDates(preset).end);
|
||
|
|
|
||
|
|
return { startDate, endDate, setStartDate, setEndDate };
|
||
|
|
}
|