使用Javascript获得工作日

haw*_*awx 8 javascript

我想在两个约会之间得到工作日.示例:stdate = 28/10/2011 and endate = 04/11/2011.这应该是6个工作日,但它只给5天.

var workingdays = 0;
var weekday     = new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

while (stdate <= endate) 
{
    var day = weekday[stdate.getDay()];
    if(day != "Saturday" && day != "Sunday") 
    {
        workingdays++; 
    }
    console.log(weekday[stdate.getDay()]);
    stdate = new Date(stdate.getTime() + 86400000); 
}
Run Code Online (Sandbox Code Playgroud)

控制台日志显示以下结果.

Friday
Saturday
Sunday
Sunday
Monday
Tuesday
Wednesday
Thursday
Run Code Online (Sandbox Code Playgroud)

由于某种原因,周日出现两次.任何帮助,将不胜感激.

Bas*_*ter 10

干得好:

 function getWorkingDays(startDate, endDate){
     var result = 0;

    var currentDate = startDate;
    while (currentDate <= endDate)  {  

        var weekDay = currentDate.getDay();
        if(weekDay != 0 && weekDay != 6)
            result++;

         currentDate.setDate(currentDate.getDate()+1); 
    }

    return result;
 }

 var begin = new Date(2011, 09, 8);
 var end = new Date(2011, 09, 25);
 alert(getWorkingDays(begin, end)); // result = 12 days
Run Code Online (Sandbox Code Playgroud)

请记住,两个变量的月份指示基于零.所以在我的例子中我们看的是十月(第10个月).

  • 我改变了var currentDate = startDate; to var currentDate = new Date(startDate.getTime()); 避免startDate变量的变异. (3认同)

Guf*_*ffa 6

夏令时.

由于你要在24小时内添加日期,所以在周日的第二天还不足以让你到达,因为那个特别的星期天有25个小时.

您应该添加一天而不是添加小时:

stdate = new Date(stdate.getFullYear(), stdate.getMonth(), stdate.getDate() + 1);
Run Code Online (Sandbox Code Playgroud)

说明:当您Date使用超出范围的日期调用构造函数时,它将自动换行到下个月,即为new Date(2010,9,32)您提供11月的第一个月.