只计算javascript中的工作时间

时间:2017-10-17 12:38:29

标签: javascript

我目前正在努力计算数小时。不包括外面的营业时间,周末和银行的

bHols = [........]

function calc_hours_open(ps_mx) {
    var hoursOpen = 0
    var current = ps_mx

    //Working Hours
    var workStart = 8;
    var workStop = 18;
    var d = new Date(current)
    var endDate = new Date()

    while(current <= endDate) {          
        let currHour = d.getHours()
        let currDay = current.day()         

        if(currHour >= workStart && currHour < workStop && 
            currDay !== 0 && currDay !== 6 && 
            bHols.indexOf(current.format('DD/MM/YYYY')) == -1) {
            hoursOpen++;
        }

        current = current.add(1, 'hours')
    }

    return hoursOpen
}

问题是,它增加了24小时而不仅仅是8到18之间的10个工作小时 所以当它应该只有20小时我才能得到48。

例如

ps_mx = 10/10/2017 11:30:00  bHols = [........]

function calc_hours_open(ps_mx) {
    var hoursOpen = 0
    var current = ps_mx

    //Working Hours
    var workStart = 8;
    var workStop = 18;
    var d = new Date(current)
    var endDate = new Date()
    console.log(d)
    console.log(endDate)
    while(current <= endDate) {          
        let currHour = d.getHours()
        let currDay = current.day()
        console.log(currHour)         
        console.log(currDay)
        if(currHour >= workStart && currHour < workStop && 
            currDay !== 0 && currDay !== 6 && 
            bHols.indexOf(current.format('DD/MM/YYYY')) == -1) {
            hoursOpen++;
        }

        current = current.add(1, 'hours')
    }

    return hoursOpen
}

console.log(hoursOpen)使用函数

按顺序登录

10/10/10 11:30:00

17/10/2017 14:00:00

11

1(每天递增)

147

2 个答案:

答案 0 :(得分:1)

我相信我发现了问题

您的if声明中的检查是否正在测试当前日期是否在工作时间内。更改应该在您的代码的这一部分:

let currHour = d.getHours() //d, in your code, is new Date()

if(currHour >= workStart && currHour < workStop && 
        currDay !== 0 && currDay !== 6 && 
        bHols.indexOf(current.format('DD/MM/YYYY')) == -1)

我相信你应该从current获得currHour - 这是你正在测试的(并在循环中递增)...... d.getHours()永远不会在循环中改变...

答案 1 :(得分:0)

固定

bHols = [........]

function calc_hours_open(ps_mx) {
var hoursOpen = 0
var current = ps_mx

//Working Hours
var workStart = 8;
var workStop = 18;
var d = moment(current)
var endDate = moment()

while(d <= endDate) {          
    let currHour = d.hour()
    let currDay = d.day()         

    if(currHour >= workStart && currHour < workStop && 
        currDay !== 0 && currDay !== 6 && 
        bHols.indexOf(current.format('DD/MM/YYYY')) == -1) {
        hoursOpen++;
    }

    d = d.add(1, 'hours')
}

return hoursOpen

}