Files
sam-react-prod/src/hooks/useDateRange.ts

61 lines
1.9 KiB
TypeScript
Raw Normal View History

'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 };
}