컴퓨터 Javascript 해당 연월의 마지막 날짜 가져오기
2020.11.25 23:55
날짜 검증할 때 필요한 경우가 있음.
아래는 Date Object 일 때
/**
* @type : prototype_function
* @access : public
* @desc : 자바스크립트의 내장 객체인 Date 객체에 lastDay 메소드를 추가한다. lastDay 메소드는 해당 년월의 마지막 일자를 반환한다.
* <pre>
* var date = new Date(2019, 1, 6); // 2019-02-06 00:00:00
* var lastDayOfFeb = date.lastDay(); ==> 2019-02-28 00:00:00
* </pre>
* 위의 예에서 date 변수는 현재 날짜/시각 Date에서 구분과 입력값에 따라 변경될 Date 객체이다.
* <pre>
* </pre>
* @return : Date Object.
* @author :
*/
Date.prototype.lastDay = function() {
var returnDate = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds());
returnDate.setFullYear(this.getFullYear(), this.getMonth() + 1, 0);
return returnDate;
};
다음은 위를 이용해서 연월만 입력받으면 마지막 날을 리턴해주는 것. 단 isNull, lastDay() 같은 것은 이 게시판에 게재해놓은 것들의 재활용이니까, 그것까지 선언해주지 않으면 오류 발생한다.
/**
* @type : function
* @access : public
* @desc : 연도, 월을 입력받아 마지막 날짜를 return 한다.
* <pre>
* var lastDayOfFeb = getLastDayOfMonth(2019, 2); ==> 2019-02-28 00:00:00
* </pre>
* 위의 예에서 date 변수는 현재 날짜/시각 Date에서 구분과 입력값에 따라 변경될 Date 객체이다.
* <pre>
* inpYear : 연도
* inpMonth : 월
* </pre>
* @return : Date Object
* @author :
*/
function getLastDayOfMonth(inpYear, inpMonth)
{
var year = parseInt(inpYear);
var month = parseInt(inpMonth);
if(!isNull(year) && !isNull(month))
{
var returnDate = new Date(year, month - 1);
return returnDate.lastDay();
}
else
{
return null;
}
}






