Home
All Posts
🧮

[캘린더 라이브러리] 마지막 날을 계산해 다음 달이 시작하는 요일과 맞추기

Created
2024/03/05
Category
Project
3 more properties

문제의 화면

2월의 마지막 날 29일 수요일 바로 뒤에 → 3월 1일 목요일이 나와야 하는데, 아래와 같이 한 칸을 건너 뛰고 금요일부터 시작하고 있다. 왜 이렇게 된 것일까?
중간에 목요일에 텅 비어있다

수정 전 코드

const getExtraDaysForMonth = (year: number, month: number, daysInMonth: number) => { const firstDayCurrentMonth = new Date(year, month, 1).getDay(); const lastDayCurrentMonth = new Date(year, month + 1, 0).getDay(); const prevMonthLastDate = new Date(year, month, 0).getDate(); const prevMonthStartDay = firstDayCurrentMonth === 0 ? 6 : firstDayCurrentMonth - 1; const prevMonthDays = Array.from({ length: prevMonthStartDay }, (_, i) => prevMonthLastDate - i).reverse(); const nextMonthStartDay = lastDayCurrentMonth === 6 ? 0 : lastDayCurrentMonth + 1; const nextMonthDays = Array.from({ length: 7 - nextMonthStartDay }, (_, i) => i + 1); const totalDays = prevMonthDays.length + 7 * Math.ceil((daysInMonth + nextMonthDays.length) / 7); const additionalNextMonthDays = totalDays - (daysInMonth + prevMonthDays.length); return { prevMonthDays, nextMonthDays: nextMonthDays.concat(Array.from({ length: additionalNextMonthDays }, (_, i) => i + nextMonthDays.length + 1)) }; };
TypeScript
복사

원인 파악

일요일부터 시작하는 한 주가 나타나는 레이아웃을 보장하기 위해 현재 달의 첫 번째 날이 무슨 요일인지에 따라 필요한 이전 달의 날짜를 계산해야 하는데, 첫 날짜가 일요일인 경우에만 6일을 반환하고 있었다.

문제 해결 방향

이전 달의 마지막 날부터 날짜를 추가하지 않고, 첫 날짜가 시작되는 요일에 맞춰서 필요한 날짜를 계산하도록 한다.

수정 후 코드

const getExtraDaysForMonth = (year: number, month: number, daysInMonth: number) => { const firstDayCurrentMonth = new Date(year, month, 1).getDay(); // 이전 달의 마지막 날짜를 구하기 const prevMonthLastDate = new Date(year, month, 0).getDate(); // 필요한 이전 달의 날짜 수를 계산하기 ✅ const daysFromPrevMonth = firstDayCurrentMonth !== 0 ? firstDayCurrentMonth : 7; // 이전 달의 날짜를 담을 배열을 만들기 const prevMonthDays = Array.from({ length: daysFromPrevMonth }, (_, i) => prevMonthLastDate - i).reverse(); const lastDayCurrentMonth = new Date(year, month + 1, 0).getDay(); // 필요한 다음 달의 날짜 수를 계산하기 ✅ const nextMonthStartDay = lastDayCurrentMonth === 6 ? 0 : lastDayCurrentMonth + 1; const totalDays = prevMonthDays.length + daysInMonth; const requiredNextMonthDays = 7 - nextMonthStartDay; const additionalDays = (Math.ceil(totalDays / 7) * 7) - totalDays; const nextMonthDaysLength = requiredNextMonthDays + additionalDays; // 다음 달의 날짜를 담을 배열을 만들기 const nextMonthDays = Array.from({ length: nextMonthDaysLength }, (_, i) => i + 1); return { prevMonthDays, nextMonthDays }; };
TypeScript
복사
위의 코드를 보면, daysFromPrevMonth는 현재 달의 첫 날이 시작하는 요일에 맞추어 이전 달의 날짜가 필요한 수만큼 계산되어 배열에 추가된다. 그리고 nextMonthDaysLength는 다음 달의 날짜 수가 달력의 마지막 행을 채우는 데 필요한 정확한 수를 계산하여 배열에 추가한다.

수정된 화면

지난 달 마지막 날짜와 요일에 맞게 이번 달이 시작된다.

 캘린더 라이브러리 전체 기록 바로 가기