javascript 로 이번주 7일의 날짜 구하기

Explanation

요즘 새로 공부하고 있는 것들이 많아서 블로그 포스팅에 소홀했네요.
이 포스팅은 Javascript로 이번주 7일의 날짜를 구하는 방법입니다. (일요일부터 토요일까지)
더 좋은 방법을 아시는 분은 댓글로 알려주세요 :)

2017.06.29 수정사항

코드에 오류가 있었네요.. 댓글로 알려주신 정보들을 참고하여 수정하였습니다.
감사합니다 :)

참고링크 :
http://pet2r.tistory.com/entry/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EA%B8%88%EC%A3%BC-%EA%B8%88%EC%9B%94-%EA%B5%AC%ED%95%98%EA%B8%B0

수정 후 코드

var currentDay = new Date();  
var theYear = currentDay.getFullYear();
var theMonth = currentDay.getMonth();
var theDate  = currentDay.getDate();
var theDayOfWeek = currentDay.getDay();

var thisWeek = [];

for(var i=0; i<7; i++) {
  var resultDay = new Date(theYear, theMonth, theDate + (i - theDayOfWeek));
  var yyyy = resultDay.getFullYear();
  var mm = Number(resultDay.getMonth()) + 1;
  var dd = resultDay.getDate();

  mm = String(mm).length === 1 ? '0' + mm : mm;
  dd = String(dd).length === 1 ? '0' + dd : dd;

  thisWeek[i] = yyyy + '-' + mm + '-' + dd;
}

console.log(thisWeek);

수정 전 코드

	// 결과
	var value = [];

	// 오늘의 요일 및 날짜
	var currentDay = new Date();  
	var theYear = currentDay.getFullYear();
	var theMonth = Number(currentDay.getMonth()) + 1;
	var theDate  = Number(currentDay.getDate());
	var theDay  = Number(currentDay.getDay());

	// 날짜 업데이트
	var newYear, newMonth, newDate;

	// 이번달 마지막날
	var nowLast = new Date ();
		nowLast.setMonth(nowLast.getMonth() + 1);
	var nowLastDay = new Date( nowLast.getYear(), nowLast.getMonth(), "");
		nowLastDay = nowLastDay.getDate();

	var lastDay; // 이전 달 마지막날 파악

	for (var i = -theDay; i < (theDay-7)*-1; i++){

	    newYear = theYear;
	    newDate = theDate;
	    newMonth = theMonth;

		//첫주 일때
		if(theDate+i < 1){
	        
			if(theMonth == 1){ // 1월 첫째주 일때
				lastDay = new Date(Number(currentDay.getFullYear())-1, Number(currentDay.getMonth())+12, "");
			} else { // 1월 첫째주가 아닐때
				lastDay = new Date(currentDay.getFullYear(), currentDay.getMonth(), "");
			}

			newYear = lastDay.getFullYear();
			newMonth = lastDay.getMonth();
			newDate = Number(lastDay.getDate())+i;

		//마지막주 일때
		} else if( theDate+i > nowLastDay) {

			if(theMonth == 12){ // 12월 마지막주 일때
				newYear = Number(theYear) + 1;
			}

			newMonth = Number(theMonth) + 1;
			newDate = i;

		}

	    newDate = (newDate + i);
	    
	    // yyyy-mm-dd 형식으로
	    if(String(newDate).length < 2){
	        newDate = "0" + String(newDate);
	    }
	    if(String(newMonth).length < 2){
	        newMonth = "0" + String(newMonth);
	    }


		//이번주 7일의 날짜를 value에 담는다.
		value.push(newYear + "-" + newMonth + "-" + newDate);
	}

	console.dir(value);
이전 댓글 8개
  1. cheolguso

    데이트 객체에 대해 한번 자세히 알아봐야겠어요ㅎ 좋은 참고 글 감사합니다 :)

  2. cheolguso

    안녕하세요~ 제가 너무 확인이 늦었네요... 도움이 되었다니 저도 기쁘네요. 댓글 남겨주셔서 감사합니다 :)

  3. 주인장님복받으세요

    ㅜㅜㅜㅜㅜ완전 감사합니다...진짜 복받으실거예용...

  4. cheolguso

    안녕하세요? 코드에 오류가 있었는데 오랫동안 몰랐네요... 아래에 '더 좋은 방법'님이 알려주신 글을 참고해서 코드를 수정하였습니다. 조금이나마 도움이 되었으면 좋겠네요~ 댓글 남겨주셔서 감사합니다 :)

  5. 더 좋은 방법

    Date 객체의 function에 대한 이해가 잘 되어 있으면 코드량을 많이 줄일수 있습니다. http://pet2r.tistory.com/entry/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%EA%B8%88%EC%A3%BC-%EA%B8%88%EC%9B%94-%EA%B5%AC%ED%95%98%EA%B8%B0 시작일과 종료일만을 구하는 방법 이긴한데, 응용해서 사용하면 될 것 같네요.

  6. 오류가있어요

    헝..근데 밑소스로 첫주를 하니깐 결과가 또 이상하네요ㅠㅠㅠㅠㅠㅠ 무튼 댓글폭탄이 된거같아서 죄송해요 일단 다른 소스를 구해서 해야겠네요... ㅠ

  7. 오류가있어요

    안녕하세요.. 이거~ 이번주는 뭔가 이상하게 나오네요ㅠㅠ 이번주의 끝은 2017-07-01 이어야하는데 2017-07-08로 계속 나옵니다... 소스 보고는 있는데 제가 만든게 아니라서 그런지 조금 어려운감이 있네요 혹시 보게 되신다면 수정요청을 부탁드리겠습니다ㅠ

  8. 오류가있어요

    제가 좀 수정을 해봤는데 일단 8월까지는 검증을 해봤어요. 근데 이후로는 어찌될지 모르겠네용.. 일단 첫 주랑 마지막 주 비교 후에 newDate에 i값을 더하셔서 그걸 newDate에 담으셨는데 저는 첫 주, 마지막 주 비교 전에 newDate = (newDate + i);를 했습니다. 그러고 첫 주, 마지막 주 비교할 때 변수명을 newDate로 바꿨어요. 그러고 마지막 주 일 때 newDate = i; 대신에 newDate = newDate - nowLastDay;로 수정했습니다... 수정된 for문 올릴게여... 근데 소스가 올라갈지 모르겠네요 for (var i = -theDay; i &lt; (theDay-7)*-1; i++){ newYear = theYear; newDate = theDate; newMonth = theMonth; newDate = (newDate + i ); // console.log(newDate); //첫주 일때 if(newDate+i nowLastDay) { if(theMonth == 12){ // 12월 마지막주 일때 newYear = Number(theYear) + 1; } newMonth = Number(theMonth) + 1; newDate = newDate - nowLastDay ; //console.log("마지막 주 일 때 : " + newMonth + "," + newDate); } // yyyy-mm-dd 형식으로 if(String(newDate).length &lt; 2){ newDate = &quot;0&quot; + String(newDate); } if(String(newMonth).length &lt; 2){ newMonth = &quot;0&quot; + String(newMonth); } //이번주 7일의 날짜를 value에 담는다. value.push(newYear + &quot;-&quot; + newMonth + &quot;-&quot; + newDate); }