gpt4 book ai didi

javascript - 如何获取一个月中不包括周末的天数

转载 作者:行者123 更新时间:2023-12-03 23:51:06 26 4
gpt4 key购买 nike

我写了一个函数来给我一个月的所有日子,不包括周末。一切正常,但是当我想获得 12 月的天数时,Date 对象返回下周的 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))

最佳答案

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

这也适用于您获取月份时 - 它还返回 0 到 11

我很惊讶你说

Every thing works fine



它实际上从来没有工作过任何一个月 - 总是会返回一个空数组
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))

关于javascript - 如何获取一个月中不包括周末的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39296064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com