¿Obtener el número de días en un mes específico usando JavaScript?
Posible duplicado:
¿Cuál es la mejor manera de determinar el número de días en un mes con JavaScript?
Di que tengo el mes como un número y un año.
Respuesta #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
En aras de una claridad explícita en medio de la confusión del índice cero, aquí hay un ejemplo interactivo:
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>Respuesta #2
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
Respuesta #3
Lo siguiente toma cualquier valor de fecha y hora válido y devuelve el número de días en el mes asociado... elimina la ambigüedad de ambas otras respuestas...
// pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
return new Date(anyDateInMonth.getFullYear(),
anyDateInMonth.getMonth()+1,
0).getDate();}
Respuesta #4
Otra opción posible sería usar Datejs
Entonces puedes hacer
Date.getDaysInMonth(2009, 9)
Aunque agregar una biblioteca solo para esta función es excesivo, siempre es bueno conocer todas las opciones que tienes disponibles :)
