计算一个月内的周末

时间:2017-08-24 13:44:54

标签: javascript date

我想构建一个简单的函数来接收特定月份来检查。作为回报,它将提供该月内计算的周末天数。

在代码中我假设当前年份是简化任务的相关年份。

问题是,在翻看日历并手动计算时,它实际上没有为周末返回正确的答案。

workDays(4); // submitting the month to check for

function workDays(monthCheck) //Calculate the actual work days: eliminate weekends from month
{
  // init month to check as proper date variable and setting days to 0 for total days
  var month = new Date(new Date().getFullYear(), monthCheck+1, 0);
  var daysOff = 0; //init

 for(i = month.getDate(); i>=0; i--) //check for days that = 0 or 6 (Sunday OR Saturday)
  {

     if(new Date(month.getFullYear(), monthCheck, i).getDay() == 0 || new Date(month.getFullYear(), monthCheck, i).getDay() == 6)
      {
        console.log(daysOff++); // weekend day added to weekend days counter
      }
  }
  return console.log("The days off for the month of " + (month.getMonth()) + " are " + daysOff + " days off.");
}

3 个答案:

答案 0 :(得分:0)

不确定你哪里出错但this似乎是对的:

var d = new Date();
var getTot = daysInMonth(d.getMonth(),d.getFullYear());
var weekends = new Array();

for(var i=1;i<=getTot;i++){
    var newDate = new Date(d.getFullYear(),d.getMonth(),i)
    if(newDate.getDay()==0 || newDate.getDay()==6){
        weekends.push(i)
    }

}
console.log(weekends.length);

function daysInMonth(month,year) {
    return new Date(year, month, 0).getDate();
}

答案 1 :(得分:0)

我觉得你的逻辑很混乱。我将代码重构为(imo)更易读的版本,结果似乎符合预期:

nonWorkDays(4);

function nonWorkDays(month)
{
  var current = new Date(new Date().getFullYear(), month - 1, 1);
  var daysOff = 0; //init

  // as long as our date is in the requested month
  while (current.getMonth() == month -1) {
    // saturday or sunday?
    if (current.getDay() == 0 || current.getDay() == 6) {
      daysOff++; 
      console.log(daysOff, current); 
    }

    // move to next day
    current.setDate(current.getDate() + 1);
  }
  console.log("The days off for the month of " + month + " are " + daysOff + " days off.");

  return daysOff;
}

一个小提琴演示:https://jsfiddle.net/4kmtemfy/

答案 2 :(得分:0)

您的问题是monthCheck+1。由于几个月是零索引,并且您想要下个月的月份数,不要减去1.您还可以稍微简化逻辑:

&#13;
&#13;
function workDays(monthCheck) {
  // Create date for last day of month to check
  var month = new Date(new Date().getFullYear(), monthCheck, 0);
  var daysOff = 0;

  // For each day of the month
  for(var i = month.getDate(); i>=0; i--) {
    // Add day off for Saturday and Sunday
    if (!(month.getDay()%6)) {
      daysOff++;
    }
    month.setDate(month.getDate()-1);
  }
  return daysOff;
}

var month = 4;
console.log('Days off for ' + month + ' are ' + workDays(month) + '.');
&#13;
&#13;
&#13;