Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of days in a month excluding weekends

Tags:

javascript

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))
like image 387
Fury Avatar asked Sep 02 '16 15:09

Fury


1 Answers

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))
like image 190
Jaromanda X Avatar answered Oct 12 '22 19:10

Jaromanda X