[Front구현] 주간 달력 구하기
아래는 로직 아이디어입니다
날짜 로드 -> ok
마지막날 첫 날 처리 ->no
요일 인덱스 ( 월 0 화 1 수 2 목 3 금 4 토 5 일 6 )
getCurrentWeek => { 오늘날짜 / 오늘 달 / 오늘 날짜일주일의 시작 / 이번주 모든 요일
오늘날짜 => new Date()
오늘 달 => new Date().getMonth()
오늘날짜의 일주일의 시작 (firstDayOfWeek) => 오늘날짜(12일 수) - 요일인덱스( 2 ) = 10이 일요일날짜
이번주 요일 [] => for문. i = 0 부터 6까지 , date = 날짜 객체 ( 앞으로 변경될 temp날짜변수 ) - date에 i 더하기 , 만약 구한 date가 현재 month의 마지막 날짜보다 크다면 1로 설정하여 다음달로 넘어가게끔 -week 변수에 저장
현재 week 리턴
}
getCurrentMonth => { 오늘 날짜
오늘날짜 => new Date()
newDate.Month()리턴
}
handleLeftWeek =>{ 새로운 week 배열 저번주
newWeek = currentWeek을 현재 date의 -7 한 걸로 바꿔줌.
newWeek와 newWeek의 0번째 인덱스의 Month()가 글로벌변수 currentWeek과 month의 새로운 값
}
handleRightWeek => { 새로운 week배열 다음주
newWeek = currentWeek을 현재 date의 +7 한 걸로 바꿔줌.
newWeek와 newWeek의 0번째 인덱스의 Month()가 글로벌변수 currentWeek과 month의 새로운 값
* 우측으로가기 버튼은 어차피 다음달만 조심하면되니까
만약 currentWeek배열이 1씩커지지않는 값이 있다면 ? 다음달이된거임.
1씩 커지지않을때 ( ex 31 > 1 일때 31까지 ) 는 냅두고 그다음부터 _로채우기
그리고 다음달 처리해줘야하니까
만약 currentWeek에 _ 값이 들어있을때, 업데이트 할 땐 _이 들어있는 인덱스 전에는 _로채우고 _이 들어있는 인덱스부터 1을 채우기
만약 다음주 업데이트 때에 값이 _ 라면, 그 배열의 마지막 변수 +1을 다음주의 첫날짜로 해서 똑같이 날짜업데이트
}
이렇게해서 실행하면
잘 가다가 30 31 _ _ _ _ _ 가 나올때 다음주로 넘어가면 1 2 _ _ _ _ _ _ 과같이 계속 앞에두개만 업데이트됨.
try2
여기서 중요한데.....
30 31 _ _ _ _ _ _ 의 배열이 있다면 기존로직처럼 하면
예외 1 ) 20 21 22 23 24 25 26 > 27 28 29 30 31 32 33 : 마지막 날짜를 넘어감
예외 2 ) 30 31 _ _ _ _ _ > 37 38 ? ? ? ? ? : 어래인지 오류가 생김
예외를 어떻게 처리해야하나...?
try25
갑자기 2에서 25로 나오셔서 놀라셨ㅇ을수도있찌만
30 31 _ _ _ _ _
>버튼
_ _ 1 2 3 4 5
>버튼
1 2 8 9 10 11 12과같이
6 7 8 9 10 11 12 로 나와야하는데
_부분이 제대로 처리가안되어서 꼬였습니다.
이걸풀기위해 수많은 시간을 보냈고. 드디어 완성했습니다!!!
ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ
감격의눈물...
< Final Code >
const today = new Date();
const currentLastDaysOfYearArr = getLastDaysOfYear(today.getFullYear());
function getLastDaysOfYear(year) {
return Array.from({ length: 12 }, (_, month) => {
return new Date(year, month + 1, 0).getDate();
});
}
//캘린더
const [currentWeek,setCurrentWeek] = useState(getCurrentWeek());
const [currentMonth,setCurrentMonth] = useState(getCurrentMonth());
const currentYear = today.getFullYear();
//달이 바뀌어야하는 상태인가?
let nextMonthStart =false
function getCurrentWeek() {
const today = new Date();
const currentMonth = today.getMonth();
const firstDayOfWeek = new Date(today.setDate(today.getDate() - today.getDay()));
const week = [];
for (let i = 0; i < 7; i++) {
const date = new Date(firstDayOfWeek);
date.setDate(firstDayOfWeek.getDate() + i);
if (date.getDate() > currentLastDaysOfYearArr[currentMonth]) {
date.setDate(1);
}
week.push(date instanceof Date ? date : null); // `_` 대신 null을 사용
}
return week;
}
function getCurrentMonth() {
const todays = new Date();
return todays.getMonth();
}
function getLastDate(year, month) {
return new Date(year, month + 1, 0).getDate();
}
const handleLeftWeek = () => {
const newWeek = currentWeek.map(date => new Date(date.setDate(date.getDate() - 7)));
setCurrentWeek(newWeek);
setCurrentMonth(newWeek[0].getMonth());
};
const handleRightWeek = () => {
let tempCounting = currentWeek[6] instanceof Date ? currentWeek[6].getDate() : 0;
const newWeek = [];
for (let i = 0; i < 7; i++) {
// currentWeek[i]가 유효한 날짜 객체인지를 체크
if (currentWeek[i] !== '_' && currentWeek[i] instanceof Date) {
const lastDate = getLastDate(currentWeek[i].getFullYear(), currentWeek[i].getMonth());
// 1. _가 아닌 경우, 막날이 아닌 경우
if (currentWeek[i].getDate() + 7 <= lastDate) {
newWeek.push(new Date(currentWeek[i].setDate(currentWeek[i].getDate() + 7)));
}
// 2. 막날을 넘어가는 경우
else if (currentWeek[i].getDate() + 7 > lastDate) {
newWeek.push('_');
nextMonthStart = true;
}
}
// 3. 만약 currentWeek[i] === "_"이고, 새로운 주의 첫 날이 시작하는 경우
else if (currentWeek[i] === '_' && nextMonthStart) {
let nextMonthFirstDay = new Date(
currentWeek[0] instanceof Date ? currentWeek[0].getFullYear() : today.getFullYear(),
currentMonth + 1,
tempCounting + 1
);
newWeek.push(nextMonthFirstDay);
tempCounting++;
}
// 4. "_"인데, 달이 바뀌지 않는 경우 ==> 오류
else if (currentWeek[i] === '_' && !nextMonthStart) {
let nextMonthFirstDay = new Date(
currentWeek[0] instanceof Date ? currentWeek[0].getFullYear() : today.getFullYear(),
currentMonth,
tempCounting + 1
);
newWeek.push(nextMonthFirstDay);
tempCounting++;
}
}
// newWeek[0]이 "_"이 아니면 상태를 업데이트
if (newWeek[0] !== '_') {
setCurrentMonth(newWeek[0].getMonth());
} else {
setCurrentMonth(currentMonth + 1);
}
setCurrentWeek(newWeek);
};
아개빡쳐왼쪽로직도 오른쪽처럼지피티돌리니까 개그치짜주네또내가 직접로직작성해야하네 힘업으니까다음에한다