How to find business days in current month with Javascript?

前端 未结 2 1774
别那么骄傲
别那么骄傲 2020-12-30 18:11

How can i create function for finding numbers of business days of current month? Can you code in simple javascript without Jquery.

    function daysInMonth(i         


        
2条回答
  •  礼貌的吻别
    2020-12-30 18:38

    OK, let's solve this one piece at a time.

    The Date object in JavaScript has a method getDay. This will return 0 for Sunday, 1 for Monday, 2 for Tuesday, ... 6 for Saturday. Given that, we can conclude that we want to not count days whos getDay returns 0 or 6.

    You already have a function to return the number of days in a month, so assuming that, we can loop over all of the days and check the result of getDay. daysInMonth makes the assumption that the month is zero based; so 0 = January.

    I'd encourage you to try solving this on your own from here; otherwise read on.


    Let's start with an isWeekday function. We need the year, month, and day:

    function isWeekday(year, month, day) {
    var day = new Date(year, month, day).getDay();
    return day !=0 && day !=6;
    }
    

    We do exactly as we talked about above: we construct a Date, and use getDay to determine if it's a day.

    Now we need to loop over all of the days in the month:

    function getWeekdaysInMonth(month, year) {
    var days = daysInMonth(month, year);
    var weekdays = 0;
    for(var i=0; i< days; i++) {
        if (isWeekday(year, month, i+1)) weekdays++;
    }
    return weekdays;
    }
    

    We loop over all of the days in the month. We add 1 when checking isWeekday because the day, unlike month, is 1 based. If it is, we increment weekdays, then return.

    So we can use getWeekdaysInMonth like this:

    var weekdays = getWeekdayInMonth(9, 2011); //9 = October.
    

    Which will result in 21.

提交回复
热议问题