更改日期,使其在营业时间内

时间:2018-10-17 17:52:32

标签: javascript datetime pentaho pentaho-spoon pentaho-data-integration

在Pentaho Data Integration的JavaScript步骤中,我想以小时为单位计算从一个日期到另一个日期的时间。

在遵循此this blog post之后,我意识到我需要调整函数中的startDate和endDate值,这些值在下班时间之外,因此它们在上班时间之内,因此该函数不会返回零。日期格式为09/27/2018 18:54:55。

到目前为止,这是我的尝试:

var Approve_Gap;
var created_at_copy;
var approved_at_copy1;


// Function that accepts two parameters and calculates
// the number of hours worked within that range
function workingHoursBetweenDates(startDate, endDate) {  
    // Store minutes worked
    var minutesWorked = 0;

    // Validate input
    if (endDate < startDate) { return 0; }

    // Loop from your Start to End dates (by hour)
    var current = startDate;

    // Define work range
    var workHoursStart = 8;
    var workHoursEnd = 17;
    var includeWeekends = true;

    // bring dates into business hours

    if(current.getHours() > workHoursEnd) {
        current = current - (current.getHours() - workHoursEnd);
    }

    else if(current.getHours() < workHoursStart) {
        current = current + (workHoursStart - current.getHours()) 
    }

    if(endDate.getHours() > workHoursEnd) {
        endDate = endDate - (endDate.getHours() - workHoursEnd);
    }

    else if(endDate.getHours() < workHoursStart) {
        endDate = endDate + (workHoursStart - endDate.getHours()) 
    }

    // Loop while currentDate is less than end Date (by minutes)
    while(current <= endDate){   

        // Is the current time within a work day (and if it 
        // occurs on a weekend or not)          
        if(current.getHours() >= workHoursStart && current.getHours() < workHoursEnd && (includeWeekends ? current.getDay() !== 0 && current.getDay() !== 6 : true)){
              minutesWorked++;
        }

        // Increment current time
        current.setTime(current.getTime() + 1000 * 60);
    }

    // Return the number of hours
    return minutesWorked / 60;

}


Approve_Gap = workingHoursBetweenDates(created_at_copy, approved_at_copy1);

1 个答案:

答案 0 :(得分:0)

我通过调整日期副本将日期输入到营业时间,如下所示:

if(created_at_copy.getHours() >= workHoursEnd) {
    created_at_copy.setDate(created_at_copy.getDate() + 1);
    created_at_copy.setHours(8);
    created_at_copy.setMinutes(0);
    created_at_copy.setSeconds(0);

} else if(created_at_copy.getHours() < workHoursStart) {
    created_at_copy.setHours(8);
    created_at_copy.setMinutes(0);
    created_at_copy.setSeconds(0);

}

if(approved_at_copy1.getHours() >= (workHoursEnd)) {
    approved_at_copy1.setDate(approved_at_copy1.getDate() + 1);
    approved_at_copy1.setHours(8);
    approved_at_copy1.setMinutes(0);
    created_at_copy.setSeconds(0);

} else if(approved_at_copy1.getHours() < workHoursStart) {
    approved_at_copy1.setHours(8);
    approved_at_copy1.setMinutes(0);
    created_at_copy.setSeconds(0);
}