我正在嘗試創建一種方法來計算總休假天數。
我有一個包含作業日的陣列:
"作業日": [1,2,3,4,5],
所以我有兩個約會;astartDate和 an endDate,我應該在這個范圍內計算有多少天不是作業日(即總休假天數)。
例如,我有一個從 03/15(今天)到 03/21 的范圍,總共 7 天。
今天(03/15)是第 2 天,這是一個作業日,所以我不必為休息日增加計數器,而例如 03/19 不是作業日(它是第 6 天)所以我有增加休息日變數。
我試圖實作代碼,但它不能正常作業:
const checkDate = (start, end) => {
const workingDays = [1,2,3,4,5]
let dayOff = 0
var currentDate = new Date(start)
while (currentDate <= end) {
workingDays.map((day) => {
console.log('current ', currentDate.getDay(), ' day ', day)
if (currentDate.getDay() !== day) {
dayOff = 1
}
currentDate = currentDate.addDays(1)
})
}
console.log('dayOff ', dayOff)
return dayOff
}
它列印我:
LOG current 2 day 1
LOG current 3 day 2
LOG current 4 day 3
LOG current 5 day 4
LOG current 6 day 5
LOG current 0 day 1
LOG current 1 day 2
LOG current 2 day 3
LOG current 3 day 4
LOG current 4 day 5
LOG dayOff 10
但這是錯誤的,因為結果應該是 2。
我能怎么做?謝謝
編輯。
我用來添加一天的功能:
Date.prototype.addDays = function (days) {
var date = new Date(this.valueOf())
date.setDate(date.getDate() days)
return date
}
uj5u.com熱心網友回復:
currentDate = currentDate.addDays(1)
.addDays不是 Javascript 的正確功能。它在 C# 中使用。
下面是正確的代碼,它將回傳正確的答案:
const workingDays = [1,2,3,4,5]
const endDate = new Date(startDate)
let dayOff = []
var currentDate = new Date(endDate)
while (currentDate <= endDate) {
console.log('currentDate', currentDate)
let index = workingDays.indexOf(currentDate.getDay());
console.log('dayOff - index', index)
if(index == -1)
{
console.log('dayOffDate - addded', currentDate)
dayOff.push(currentDate)
}
currentDate = new Date(currentDate.setDate(currentDate.getDate() 1))
}
uj5u.com熱心網友回復:
給定第一個日期和結束日期,以下小函式將計算兩 (2) 個日期之間的總休假天數。
它很簡單,并假設結束日期與開始日期相同或更高(不檢查是否反轉日期)。
function getTotalOffDays(start,end) {
const workingDays = [1,2,3,4,5];
let daysOff = 0, // days off counter
date = new Date(start), // starting date
endDate = new Date(end); // end date
while (date <= endDate) {
if (!workingDays.includes(date.getUTCDay())) daysOff = 1; // increment days off
date = new Date(date.setUTCDate(date.getUTCDate() 1)); // go the next day
}
return daysOff;
}
console.log("Total days off: " getTotalOffDays("2022-03-15", "2022-03-21"));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445043.html
標籤:javascript 反应 反应式
