Fury Fury - 3 months ago 19
Javascript Question

How to get days in a month excluding weekends

I have written a function to give me all days of a month excluding weekends. Every thing works fine but when I want to get December days the Date object returns 01 Jan of next week and the function returns an empty array.

Any help please.

function getDaysInMonth(month, year) {
var date = new Date(year, month-1, 1);
var days = [];
while (date.getMonth() === month) {

// Exclude weekends
var tmpDate = new Date(date);
var weekDay = tmpDate.getDay(); // week day
var day = tmpDate.getDate(); // day

if (weekDay !== 1 && weekDay !== 2) {
days.push(day);
}

date.setDate(date.getDate() + 1);
}

return days;
}

alert(getDaysInMonth(month, year))

Answer

When you create a date, you use month = 0 to 11

This also goes for when you GET the month - it also returns 0 to 11

I'm surprised you said

Every thing works fine

It actually never worked for any month - always would return an empty array

function getDaysInMonth(month, year) {
    month--; // lets fix the month once, here and be done with it
    var date = new Date(year, month, 1);
    var days = [];
    while (date.getMonth() === month) {

        // Exclude weekends
        var tmpDate = new Date(date);            
        var weekDay = tmpDate.getDay(); // week day
        var day = tmpDate.getDate(); // day

        if (weekDay%6) { // exclude 0=Sunday and 6=Saturday
            days.push(day);
        }

        date.setDate(date.getDate() + 1);
    }

    return days;
}  

alert(getDaysInMonth(month, year))
Comments