달력을 만들기 위해서는 각 날짜가 어떤 월, 어떤 주에 속하는지를 계산해야 합니다.
이 기능은 getDatesInMonth라는 함수로 구현됩니다.
tsx
코드 복사
const getDatesInMonth = (monthOffset: number): CalendarData => {
const targetMonth = currentMonth.add(monthOffset, "month"); // 기준 월 계산
const startOfCalendar = targetMonth.startOf("month").startOf("week"); // 달력의 시작 날짜
const endOfCalendar = targetMonth.endOf("month").endOf("week"); // 달력의 끝 날짜
const dates: DateInfo[] = [];
let day = startOfCalendar;
while (day.isBefore(endOfCalendar) || dates.length % 7 !== 0) {
const isInCurrentMonth = day.month() === targetMonth.month(); // 현재 월에 포함 여부
dates.push({ isInCurrentMonth, day });
day = day.add(1, "day");
}
const weeks = dates.reduce((weeks: DateInfo[][], date, index) => {
if (index % 7 === 0) weeks.push([]); // 7일씩 묶기
weeks[Math.floor(index / 7)].push(date);
return weeks;
}, []);
return { weeks, dates }; // 주 단위 배열 반환
};
사용자가 달력을 보다가 "이전 달" 또는 "다음 달"로 이동하고 싶을 때, 버튼을 클릭해 이동할 수 있습니다.
tsx
코드 복사
const handleMonthChange = (offset: number) => {
setCurrentMonth(currentMonth.add(offset, "month"));
};