2011-02-03 12 views
11

Tengo una página HTML con 3 listas desplegables para el mes, el día y el año y me preguntaba si había una manera de llenar el menú desplegable correctamente según el mes y año.Javascript: calcular el número de días en el mes para un año determinado

No he hecho esto antes en el lado del cliente, pero parece que muchos controles como jQuery DatePicker lo están haciendo entre bastidores.

+1

duplicado posible: [fechas repoblar en cajas de selección] (http://stackoverflow.com/questions/4822550/repopulating-dates-on-select-boxes) –

+0

Gracias Box9! Eso es realmente lo que estaba buscando. – Abe

Respuesta

18

Se puede jugar con los objetos de fecha:

var monthStart = new Date(year, month, 1); 
var monthEnd = new Date(year, month + 1, 1); 
var monthLength = (monthEnd - monthStart)/(1000 * 60 * 60 * 24) 

aritméticas con objetos Date da un número de milisegundos.

Esto incluso funcionará para diciembre; el constructor Fecha maneja los argumentos fuera de rango envolviendo.

Nota que month está basado en cero (debe ser entre 0 y 11)

+0

Esto es increíble ... incluso funciona en años bisiestos. Probé 2/2012. ¡Gracias! – Abe

+2

Lo envolví como 'var DaysInMonth = function (año, mes) {/ * Código de SLAK aquí * /; return monthLength;}; 'y además agregó un método prototipo a Date' Date.prototype.daysInMonth = function() {var mlen = DaysInMonth (this.getFullYear(), this.getMonth()); devolver mlen; }; 'para que pueda llamar' (new DateTime (2000, 1)).daysInMonth(); ' –

+0

Marzo de 2014 devuelve 30.958333333333332 por algún motivo. – o01

25

Por lo que yo sé, no hay una función integrada (nítida) para eso. Escribí esta vez:

// note that month is 0-based, like in the Date object. Adjust if necessary. 
function getNumberOfDays(year, month) { 
    var isLeap = ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0)); 
    return [31, (isLeap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; 
} 
+1

¡Es genial cómo puedes incluir una declaración ternaria dentro de la matriz! ¡bonito! – Abe

+1

¡Esta debería ser la respuesta! ¡Brillante! – Johny

2
Date.prototype.daysinMonth: function(){ 
    var d= new Date(this.getFullYear(), this.getMonth()+1, 0); 
    return d.getDate(); 
} 

function daysinMonthfromInput(month,year){ 
    return (new Date(year,month-1,1)).daysinMonth(); 
} 

alert(daysinMonthfromInput(2,2011)); 
1

Aquí está el un trazador de líneas. Asumiendo que están diciendo enero = 1, febrero de = 2, etc .. (siendo normal) Aquí está el ejemplo del año bisiesto:

var y = 2012; 
var m = 2; 
var daysInMonth = new Date(y,m,1,-1).getDate(); 
0

estoy usando este enfoque en mi proyecto actual y encontré que necesitaba correcta para la ronda de errores Así que en lugar de utilizar monthLength en mi código, he tenido que usar esto en su lugar:

monthLength.toFixed(0) 

Por ejemplo si tengo un objeto en el que estoy almacenando un campo de fecha de texto, que puede tener este aspecto:

obj.month = theMonths[mm - 1] + " " + monthLength.toFixed(0) + ", " + obj.year; 
2

copia de otro mensaje: Get number days in a specified month using javascript?

//Month is 1 based 
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 

Todos los créditos a @c_harm, realmente gran solución

0

Puede usar esto:

var curdate = new Date(); DaysMonth = 32 - new Date (curdate.getYear(), curdate.getMonth(), 32) .getDate();

;)

-2
Date.prototype.daysinMonth= function(){ 
var d= new Date(this.getFullYear(), this.getMonth()+1, 0); 
return d.getDate(); 
}; 

function daysinMonthfromInput (month, year) { 
    return (new Date(year, month - 1, 1)).daysinMonth(); 
}; 
function fillallday (elem, month, year) { 
    var options = null; 
    var elementExists = document.getElementById(elem); 

    if (elementExists != null) { 

     this.removeOptions(elementExists); 
     var opt = document.createElement('option'); 
     opt.value = ""; 
     opt.innerHTML = "---Day---"; 
     elementExists.appendChild(opt); 
     if (month != "") { 
      if (typeof (year) === "undefined") { 
       year = new Date().getFullYear(); 
      } 
      if (year == "") { 
       year = new Date().getFullYear(); 
      } 
      var days = daysinMonthfromInput(month, year); 
      for (var i = 1; i <= days; i++) { 
       var opt = document.createElement('option'); 
       opt.value = i; 
       opt.innerHTML = i; 
       elementExists.appendChild(opt); 
      } 
     } 
    } 

} 
+0

Esta pregunta ya ha sido respondida correctamente, ¿qué agrega esta respuesta que la respuesta original no tiene? –

Cuestiones relacionadas