JavaScript / Date로 이번 달 말일 구하기와 윤년 처리
JavaScript에서 이번 달의 마지막 날짜는 다음 달의 0일을 생성해 구할 수 있습니다. new Date(연도, 현재월인덱스 + 1, 0).getDate()를 사용하며, 현재 달의 월 인덱스는 new Date().getMonth()로 얻습니다. 윤년과 12월에서 다음 해 1월로 넘어가는 경우도 날짜 계산에 반영됩니다.
다음 달 0일이 전월 말일인 이유
Date 생성자에 연도·월 인덱스·일을 넣을 때 월은 1월이 0, 12월이 11입니다. 일 자리에 0을 넣으면 지정한 월의 첫날에서 하루 전으로 정규화됩니다. 따라서 2024년 3월의 인덱스 2와 일 0을 주면 2024년 2월 29일이 됩니다. 객체를 만들려면 Date(...)가 아니라 new Date(...)를 써야 합니다.
const last = new Date(2024, 2, 0);
console.log(last.getFullYear(), last.getMonth() + 1, last.getDate());
// 2024 2 29
다음 달이 1월이면 인덱스 12가 됩니다. 생성자는 이를 다음 해 1월로 정규화하므로 12월 말일도 같은 공식으로 계산할 수 있습니다. MDN의 Date 생성자 문서에서 범위를 벗어난 날짜 구성 요소의 정규화를 확인할 수 있습니다.
현재 달과 임의의 달에 적용하기
현재 시점의 연도와 0부터 시작하는 월 인덱스를 읽어 다음 달의 0일을 생성합니다. getDate()는 그 달의 날짜 숫자 28~31을 반환합니다. 원하는 월이 1~12 형식이면 아래 함수처럼 그 값을 그대로 두 번째 인자에 전달하면 됩니다. 1월을 입력했을 때 두 번째 인자 1은 2월을 뜻하기 때문입니다.
const today = new Date();
const currentMonthLastDay = new Date(
today.getFullYear(), today.getMonth() + 1, 0
).getDate();
function lastDayOfMonth(year, month1to12) {
return new Date(year, month1to12, 0).getDate();
}
console.log(lastDayOfMonth(2024, 2)); // 29
console.log(lastDayOfMonth(2023, 2)); // 28
console.log(lastDayOfMonth(2024, 12)); // 31
예제 함수에는 유효한 연도와 1~12의 정수 월을 넘겨야 합니다. 사용자 입력을 받을 때는 범위를 검사하세요. 숫자 인자를 받는 Date 생성자는 0~99년을 1900~1999년으로 해석하므로, 그 범위의 역사적 연도를 계산하려면 다른 처리가 필요합니다. MDN의 getDate() 문서에서 반환값을 확인할 수 있습니다.
전체 예제: 연도와 월을 입력해 확인
아래 코드를 last-day.html로 저장하고 브라우저에서 엽니다. 페이지가 열리면 현재 달의 말일이 표시됩니다. 연도 2024·월 2를 입력하면 29일, 연도 2023·월 2를 입력하면 28일, 연도 2024·월 12를 입력하면 31일이 표시됩니다.
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>당월 말일 계산</title>
</head>
<body>
<h1>월의 마지막 날짜 계산</h1>
<form id="month-form">
<label>연도 <input name="year" type="number" min="1000" max="9999" required></label>
<label>월 <input name="month" type="number" min="1" max="12" required></label>
<button type="submit">계산</button>
</form>
<p id="result" role="status"></p>
<script>
function lastDayOfMonth(year, month) {
return new Date(year, month, 0).getDate();
}
const form = document.querySelector('#month-form');
const result = document.querySelector('#result');
const today = new Date();
form.elements.year.value = today.getFullYear();
form.elements.month.value = today.getMonth() + 1;
form.addEventListener('submit', event => {
event.preventDefault();
if (!form.reportValidity()) return;
const year = Number(form.elements.year.value);
const month = Number(form.elements.month.value);
const day = lastDayOfMonth(year, month);
result.textContent = `${year}년 ${month}월의 마지막 날짜는 ${day}일입니다.`;
});
form.requestSubmit();
</script>
</body>
</html>
연도는 1000~9999, 월은 1~12만 받도록 입력 필드를 제한했습니다. 이 실습은 브라우저의 현지 달력 기준으로 계산합니다. 특정 시간대의 달력을 기준으로 해야 한다면 해당 시간대의 연·월을 먼저 정한 뒤 계산해야 합니다. 계산 결과가 잘못되었다면 getMonth() 결과에 1을 중복해서 더했는지와 new를 빠뜨렸는지 확인하세요.




