我設立其產生根據開始日期和結束日期的日期數組的函數的。
該函數將接收開始和結束日期,首先格式化爲year-month-dayT12:00:00:00
格式,然後使用.getTime()
格式轉換爲毫秒。
我的腳本
我做了下面的腳本來創建陣列。
var $date_array = [];
function calc_workdays_between_dates (a, b) {
function $create_date_array ($start_date, $end_date) {
var $counter = 0;
while ($start_date !== $end_date) {
var x = new Date($start_date);
x.setDate(x.getDate() + $counter);
$date_array.push(x);
$start_date = x.getTime();
$counter++;
}
}
$create_date_array (a, b);
}
請注意,有築巢的$calc_workdays_between_dates
函數內$create_date_array
功能的原因。現在我已經剝離了$calc_workdays_between_dates
函數的所有其他部分,只關注手頭的問題(我也在對這個精簡版本進行測試 - 所以其餘的函數不會影響任何東西)。
我的問題
例1:
如果我調用該函數calc_workdays_between_dates (x1, x2);
其中:
x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 = new Date("2015-04-07")
它導致$date_array
得到以下內容:
Sat Apr 04 2015 12:00:00 GMT+0200 (CEST)
Sun Apr 05 2015 12:00:00 GMT+0200 (CEST)
Tue Apr 07 2015 12:00:00 GMT+0200 (CEST)
正如你所看到的功能出於某種原因跳過週一(總共一天)。
例2:
x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 = new Date("2015-04-10")
結果:
Sat Apr 04 2015 12:00:00 GMT+0200 (CEST)
Sun Apr 05 2015 12:00:00 GMT+0200 (CEST)
Tue Apr 07 2015 12:00:00 GMT+0200 (CEST)
Fri Apr 10 2015 12:00:00 GMT+0200 (CEST)
正如你所看到的功能在某種程度上跳過週一,週三和週四(3天總共)。
例3:
x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 = new Date("2015-04-14")
結果:
Sat Apr 04 2015 12:00:00 GMT+0200 (CEST)
Sun Apr 05 2015 12:00:00 GMT+0200 (CEST)
Tue Apr 07 2015 12:00:00 GMT+0200 (CEST)
Fri Apr 10 2015 12:00:00 GMT+0200 (CEST)
Tue Apr 14 2015 12:00:00 GMT+0200 (CEST)
正如你可以看到thise實例函數跳過週一,週三,週四,週六,週日和週一(6天總共)。
實施例4:
x1 = new Date("2015-04-04") //formatted and converted to ms before invoking function
x2 = new Date("2015-04-08")
導致功能不工作。看起來while循環繼續無休止地運行。
我的問題
是什麼使腳本跳過天?
埃姆,你的'$ create_date_array' FUNC需要一個'Date'對象,但你傳遞一個數組('X1 =新的日期(「2015-04- 04" )]')。我錯過了什麼嗎? –
@NikolaDimitroff:'$ create_date_array'函數接收以毫秒爲單位的日期,然後在執行任何計算之前將其轉換爲函數本身的日期。這是日期出現在括號內的另一個錯誤。我刪除了它們。 – rabbitco