TIP게시판

제목 이유는 알수 없는 스크립트 날짜 계산 이슈
글쓴이 kaido 작성시각 2016/09/30 17:36:45
댓글 : 0 추천 : 0 스크랩 : 0 조회수 : 9921   RSS
function dateButtonHandler(idx, start, end){
	var startObj = $("input[name='" + start + "']");
	var endObj = $("input[name='" + end + "']");
	var datePattern = "yyyy-MM-dd";
	
	var startDate = new Date();
	var endDate = new Date();
	
	if( idx == 0 ){
		startDate.setDate( startDate.getDate() + 1 );
		endDate.setDate( startDate.getDate() - 1 );
	} else if( idx == 1 ){
		endDate.setDate( startDate.getDate() - 3 );
	} else if( idx == 2 ){
		endDate.setDate( startDate.getDate() - 7 );
	} else if( idx == 3 ){
		endDate.setMonth( startDate.getMonth() - 1 );
	} else if( idx == 4 ){
		endDate.setMonth( startDate.getMonth() - 3 );
	} else if( idx == 5 ){
		startObj.val("");
		endObj.val("");
		return false;
	}

	startObj.val( endDate.format(datePattern) );
	endObj.val( startDate.format(datePattern) );
}
<div class="btn-group" id="searchDateBtns">
     <button class="btn">오늘</button>
     <button class="btn">3일간</button>
    <button class="btn">일주일</button>
    <button class="btn">1개월</button>
    <button class="btn">3개월</button>
</div>

 

이상해 보이는 부분 있습니까? 

이런 질문을 하면 다들 '문제가 있겠지?' 하고 눈을 불을 키며 위에서 아래로 볼것 입니다. ㅎㅎㅎ

 

하지만 소스 로직을 가만히 보시면 '어? 어디에도 이상 없는데?' 하실 겁니다.

 

실제로 별 문제 없이 잘 사용 되었거든요.

하.지.만. 설마 문제가 없는데 올렸을까요? ㅎㅎㅎ

 

해당 소스로 테스트해보시면 '월말' 즉 오늘같이 그 달의 말일에 테스트 하면 '오류' 가 발생 합니다.

이유는 저도 모르겠는데... 실제해보면 2016-09-29 가 아니라 2016-08-31 이라는 해괴한 값이 찍힙니다 -_-;;

 

정확한 이유는 모르겠다만, JS 의 성질이 관여되지 않을까 추측을 해봅니다.

 

아참. 해결 방법이요?

endDate.setDate( startDate.getDate() - 1 );

endDate.setDate( endDate.getDate() - 1 ); //해결

 

이유는 알수 없지만, startDate 오브젝트로 날자 계산을 한번 하면 중간에 값이 한번 바뀌나 봅니다.

그래서 endDate 오브젝트로 하면 정상출력 됩니다.

 

정확인 이유 아시는 분은 설명좀 ( ..)

 다음글 폼 전송후 뒤로가기를 막는 또 다른 방법 (4)
 이전글 php7.0.7 에서 특정 curl 관련 에러가 있네요... (6)

댓글

없음