如何得到一个月不包括周末的天数

How to get number of days in a month excluding weekends

本文关键字:不包括 周末 一个 何得      更新时间:2023-09-26

我已经写了一个函数给我一个月的所有日子,不包括周末。一切都很好,但是当我想要得到12月的日子,日期对象返回下周1月1日,函数返回一个空数组。

请帮忙。

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))

创建日期时,使用month = 0到11

当您获取月份时也是如此-它也返回0到11

我很惊讶你说

一切正常

它实际上从来没有在任何月份工作-总是返回一个空数组

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))