2011-10-31 67 views
6

我試圖讓兩個日期之間的工作日。 示例:stdate = 28/10/2011和endate = 04/11/2011。這應該是6個工作日,但它只給5天。使用Javascript獲得工作日

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

控制檯日誌顯示下面的結果。

Friday 
Saturday 
Sunday 
Sunday 
Monday 
Tuesday 
Wednesday 
Thursday 

星期天由於某種原因顯示兩次。任何幫助,將不勝感激。

+0

你如何通過你的時間(開始和結束)的javascript?你會轉換一個字符串嗎? – emt14

回答

6

夏令時。

由於您正在爲該日期添加24小時,所以僅在週日將您帶到第二天是不夠的,因爲該特定星期日有25小時。

您應該添加的一天,而不是添加時間:

stdate = new Date(stdate.getFullYear(), stdate.getMonth(), stdate.getDate() + 1); 

說明:當你調用Date構造器是超出範圍的日期,它會automaticall換到下個月,即new Date(2010,9,32)給你是十一月的第一個。

2

你可以試試這個

stdate.setDate(stdate.getDate()+1); 

代替

stdate = new Date(stdate.getTime() + 86400000); 
7

在這裏你去:

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 

請記住,這兩個變量的月顯示爲從零開始。所以在我的例子中,我們正在看十月(第十個月)。

+1

我改變了var currentDate = startDate; var var currentDate = new Date(startDate.getTime());以避免startDate變量的變化。 – Stanislav

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"; 

    var object = []; 


    function getTuesday(startDate, endDate, n) { 

     var currentDate = startDate; 
     while (currentDate <= endDate) { 
      if (weekday[currentDate.getDay()] === weekday[n]) 
       object.push(currentDate + "\n"); 
      currentDate.setDate(currentDate.getDate() + 1); 
     } return object; 
    } 

    var begin = new Date(2015, 11, 08); 

    var end = new Date(2016, 01, 08); 

    alert(getTuesday(begin, end, 3) + "\n Total date or week: " + object.length);