How to get every day of a month using Javascript?

0

How to implement an algorithm that lists every day of a given month using Javascript?

I have a combobox with the months and I need to use this combo of days according to the selected month.

    
asked by anonymous 17.12.2015 / 17:21

1 answer

3

Implemented something very fast so you have an idea, from this you can popular your Year / Month select, the function receives the month and the year. In this example I used the month of December 2015.

window.onload = function() {
    var select = document.getElementById("dias");
    var options = getDiasMes(12, 2015);
    for (var i = 0; i < options.length; i++) {
        var opt = options[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        select.appendChild(el);
    }
}

function getDiasMes(month, year) {
     month--;

     var date = new Date(year, month, 1);
     var days = [];
     while (date.getMonth() === month) {
        days.push(date.getDate());
        date.setDate(date.getDate() + 1);
     }
     return days;
}
Dia: <select id="dias"></select>
    
17.12.2015 / 17:57