Tags

, , ,

Calculating working hours between two days with JavaScript is a regular requirement in large companies. In general, managers want to measure clean performance of the employees, excluding weekends and what is outside the business hours (in my case 9 AM to 6 PM). The problem appears when you cannot use C# or Java or any other language of this type and you are limited to JavaScript. JavaScript cannot offer an elegant solution, but is still offering the functionality.

/// <Reference Name="MicrosoftAjax.js" />

function getBusinessHoursDiff(start, end) {
    /// <summary>Calculate business hours between two dates</summary>
    /// <param name="start" type="Date" maybNeNull="false" optional="false">Start date</param>
    /// <param name="end" type="Date" maybNeNull="false" optional="false">End date</param>
    var e = Function.validateParameters(arguments, [{ name: 'start', type: Date, maybNeNull: false, optional: false },
                                                    { name: 'end', type: Date, maybNeNull: false, optional: false }, ], true);

    // Passing incorrect parameters type will result in returning an empty string, you can change the logic as you wish here
    if (e) return '';

    // Define variables and clone the provides date, we do not want to modify them outside as are passed as reference
    var startDate = new Date(startDate.valueOf());
    var endDate = new Date(endDate.valueOf());
    var count = 0;

    for (var i = start.valueOf() ; i < end.valueOf() ; i = (start.setMinutes(start.getMinutes() + 1)).valueOf()) {
        if (start.getDay() != 0 && start.getDay() != 6 && start.getHours() >= 9 && start.getHours() < 18) {
            count++;
        }
    }

    return count / 60;
}

Function is simple, even to be honest I did find it after almost two days. Is also not perfect when it comes to performance as is calculating the different till seconds. Still, if you do not want to be so exact, you can calculate till hours level (setMinutes method with set setHours). I am not sure how suitable is this solution for you, but is for sure something you can start from.

Advertisements