import { format, parse, addMonths, subMonths } from 'date-fns'; import { ko } from 'date-fns/locale'; /** * 월 이름 배열 (한국어) */ export const MONTHS_KR = [ '1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월' ]; /** * 월 형식 검증 함수 (YYYY-MM 형식) */ export const isValidMonth = (month: string): boolean => { const regex = /^\d{4}-(0[1-9]|1[0-2])$/; return regex.test(month); }; /** * 현재 년월 가져오기 */ export const getCurrentMonth = (): string => { return format(new Date(), 'yyyy-MM'); }; /** * 이전 월 가져오기 */ export const getPrevMonth = (month: string): string => { // 입력값 검증 if (!isValidMonth(month)) { console.warn('유효하지 않은 월 형식:', month); return getCurrentMonth(); } try { // 월 문자열을 날짜로 파싱 const date = parse(month, 'yyyy-MM', new Date()); // 한 달 이전 const prevMonth = subMonths(date, 1); // yyyy-MM 형식으로 반환 return format(prevMonth, 'yyyy-MM'); } catch (error) { console.error('이전 월 계산 중 오류:', error); return getCurrentMonth(); } }; /** * 다음 월 가져오기 */ export const getNextMonth = (month: string): string => { // 입력값 검증 if (!isValidMonth(month)) { console.warn('유효하지 않은 월 형식:', month); return getCurrentMonth(); } try { // 월 문자열을 날짜로 파싱 const date = parse(month, 'yyyy-MM', new Date()); // 한 달 이후 const nextMonth = addMonths(date, 1); // yyyy-MM 형식으로 반환 return format(nextMonth, 'yyyy-MM'); } catch (error) { console.error('다음 월 계산 중 오류:', error); return getCurrentMonth(); } }; /** * 표시 형식으로 변환 (yyyy년 MM월) */ export const formatMonthForDisplay = (month: string): string => { try { // 입력값 검증 if (!isValidMonth(month)) { console.warn('유효하지 않은 월 형식:', month); return format(new Date(), 'yyyy년 MM월', { locale: ko }); } // 월 문자열을 날짜로 파싱 const date = parse(month, 'yyyy-MM', new Date()); // yyyy년 MM월 형식으로 반환 (한국어 로케일) return format(date, 'yyyy년 MM월', { locale: ko }); } catch (error) { console.error('월 형식 변환 중 오류:', error); return month; } };