2011-02-03 60 views
11

Ho una pagina HTML con 3 menù a discesa per il mese, il giorno e l'anno e mi chiedevo se ci fosse un modo per popolare la caduta di mese in modo corretto a seconda del mese e anno.Javascript: calcolare il numero di giorni in mese per un dato anno

non l'ho fatto prima sul lato client, ma sembra che un sacco di controlli, come il jQuery DatePicker stanno facendo che dietro le quinte.

+1

Eventuali duplicati: [date ripopolare su selezionare le caselle] (http://stackoverflow.com/questions/4822550/repopulating-dates-on-select-boxes) –

+0

Grazie Box9! Questo è in realtà quello che stavo cercando. – Abe

risposta

18

Si può giocare con gli oggetti di data:

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

aritmetica con Date oggetti dà un numero di millisecondi.

Questo funziona anche per dicembre; il costruttore Date gestisce gli argomenti fuori range avvolgendo.

noti che month è a base zero (deve essere compreso tra 0 e 11)

+0

Questo è fantastico .. funziona anche negli anni bisestili. Ho provato il 2/2012. Grazie! – Abe

+2

L'ho avvolto come 'var DaysInMonth = function (year, month) {/ * codice SLAK qui * /; return monthLength;}; 'e ulteriormente aggiunto un metodo prototype alla Data' Date.prototype.daysInMonth = function() {var mlen = DaysInMonth (this.getFullYear(), this.getMonth()); return mlen; }; 'così posso chiamare' (new DateTime (2000, 1)).daysInMonth(); ' –

+0

marzo 2014 restituisce 30.958333333333332 per qualche motivo. – o01

25

Per quanto ne so, non c'è (puro) funzione built-in per questo. Ho scritto una volta:

// 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

È fantastico come si possa includere un'istruzione ternaria all'interno dell'array! simpatico! – Abe

+1

Questa dovrebbe essere la risposta! 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

Ecco quello liner. si Supponendo che stanno dicendo gennaio = 1 febbraio = 2, ecc .. (essendo normale) Ecco l'esempio anno bisestile:

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

Sto usando questo approccio nel mio progetto attuale e scoperto che avevo bisogno corretta per turno off errori. Così, invece di usare monthLength nel mio codice, ho dovuto utilizzare questo, invece:

monthLength.toFixed(0) 

Per esempio se ho un oggetto in cui sono la memorizzazione di un campo data di testo, può assomigliare a questo:

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

Copia da un altro post: 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 

tutti i crediti per @c_harm, davvero grande soluzione

0

Si può effettivamente utilizzare questo:

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

Questa domanda ha già avuto una risposta corretta: cosa aggiunge questa risposta che la risposta originale non ha? –

Problemi correlati