JavaScript を使用して指定した月の日数を取得しますか? [重複] 質問する

JavaScript を使用して指定した月の日数を取得しますか? [重複] 質問する

重複の可能性あり:
JavaScript を使用して月の日数を判断する最適な方法は何ですか?

たとえば、月を数字で表し、年を表わすとします。

ベストアンサー1

// Month in JavaScript is 0-indexed (January is 0, February is 1, etc), 
// but by using 0 as the day it will give us the last day of the prior
// month. So passing in 1 as the month number will return the last day
// of January, not February
function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}

// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29

ゼロインデックスの混乱の中で明確に理解するために、インタラクティブな例を示します。

function daysInMonth (month, year) {
  return new Date(parseInt(year), parseInt(month) + 1, 0).getDate();
}

//---------- iteraction stuff -----

const byId = (id) => document.getElementById(id);
const monthSelect = byId("month");
const yearSelect = byId("year");

const updateOutput = () => { 
  byId("output").innerText = daysInMonth(monthSelect.value, yearSelect.value)
}
updateOutput();

[monthSelect, yearSelect].forEach((domNode) => { 
  domNode.addEventListener("change", updateOutput)
})
Month: <select id="month">
  <option value="0">Jan</option>
  <option value="1">Feb</option>
  <option value="2">Mar</option>
  <option value="3">Apr</option>
  <option value="4">May</option>
  <option value="5">Jun</option>
  <option value="6">Jul</option>
  <option value="7">Aug</option>
  <option value="8">Sep</option>
  <option value="9">Oct</option>
  <option value="10">Nov</option>
  <option value="11">Dec</option>
</select>
<br>
Year: <select id="year">
  <option value="2000">2000 (leap year)</option>
  <option value="2001">2001</option>
  <option value="2002">2002</option>
  <option value="2003">2003</option>
</select>
<br>

Days in month: <span id="output"></span>

おすすめ記事