Home
All Posts
🔢

[캘린더 라이브러리] 12월이 00월로 표시되고, 1월이 13월로 표시되는 버그

Created
2024/03/08
Category
Project
3 more properties

문제의 화면

아래의 두 가지 버그가 동시에 발생했고, 두 버그가 서로 연관이 있다고 판단되어 핸들러 함수를 살펴보았다.
1월 달력에서 12월 날짜를 클릭하면 12월00월로 표시되는 버그
12월 달력에서 1월 날짜를 클릭하면 1월13월표시되는 버그
12월이 00월로 표시된다.
1월13월로 표시된다.

기존 코드

const handleDateSelect = (year: number, month: number, day: number) => { // 선택된 날짜의 문자열 포맷을 생성 const newDate = new Date(year, month - 1, day); setCurrentDate(newDate); // 현재 날짜 상태를 업데이트 // 포맷팅된 날짜로 상태 업데이트 const formattedDate = `${year}/${month < 10 ? `0${month}` : month}/${day < 10 ? `0${day}` : day}`; setDisplayDate(formattedDate); // DateInputContainer에 표시될 날짜를 업데이트 setDateInput(formattedDate); // CalendarInput에도 날짜를 업데이트 };
TypeScript
복사

수정된 코드

아래와 같이 버튼 클릭 시 작동하는 핸들러 중간에 조건문을 넣어 계산이 되도록 했더니 해결되었다.
const handleDateSelect = (year: number, month: number, day: number) => { let newYear = year; let newMonth = month - 1; // JavaScript의 Date 객체는 0부터 11까지 월을 나타냄 // 이전 달 날짜 클릭 시 년/월 조정 if (month === 0) { newYear = year - 1; newMonth = 11; // 12월 } // 다음 달 날짜 클릭 시 년/월 조정 if (month === 13) { newYear = year + 1; newMonth = 0; // 1월 } const newDate = new Date(newYear, newMonth, day); setCurrentDate(newDate); // 포맷팅된 날짜로 상태 업데이트 const formattedMonth = newMonth + 1 < 10 ? `0${newMonth + 1}` : `${newMonth + 1}`; const formattedDay = day < 10 ? `0${day}` : `${day}`; const formattedDate = `${newYear}/${formattedMonth}/${formattedDay}`; setDisplayDate(formattedDate); setDateInput(formattedDate); };
TypeScript
복사

해결된 화면

12월이 12월로 잘 나온다.
1월이 1월로 잘 나온다.