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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With