Sep 12, 2011

Calculate business days in JavaScript (with variable business days per week)

There are lot of ways to calculate working days. Anyway, it was not easy to find a method to calculate business days if the number of working days per week is being changed. By default, working days will be Monday to Friday, but in some cases you might need to calculate days including Saturday or both Saturday and Sunday.

In my case it was required to calculate the cost of hire when renting equipments. They are to be charged according to the days they are being used. Some factories could work just 5 days while some work for 6 or 7 days per week.

I couldn’t find any method in the web to do it in client side. Below is the only way I could think of. Actually hint was given by one of the colleagues.

calcBusinessDaysExtended = function (Start, End, DaysPerWeek)
{
    Start.setHours(0);
    End.setHours(0);

    _StartUTCmilli = Date.UTC(Start.getFullYear(), Start.getMonth(), Start.getDate());
    _EndUTCmilli = Date.UTC(End.getFullYear(), End.getMonth(), End.getDate());
    var _Days = Math.floor((_EndUTCmilli - _StartUTCmilli) / 86400000) + 1;

    var _Saturdays = 0;
    var _Sundays = 0;
    var _bdays = 0;

    var nextDatOfEnd = new Date(End.setDate(End.getDate() + 1));
    for (i = Start; i < nextDatOfEnd; i.setDate(i.getDate() + 1))
    {
        if (i.getDay() == 6) { _Saturdays = _Saturdays + 1; }
        if (i.getDay() == 0) { _Sundays = _Sundays + 1; }
    }

    switch (DaysPerWeek)
    {
        case 5:
            _bdays = _Days - (_Saturdays + _Sundays);
            break;
        case 6:
            _bdays = _Days - _Sundays;
            break;
        default:
            _bdays = _Days;
    }
    return _bdays;
}

One can think, loops could affect the efficiency, but it is not really matters in client side work. I am happy if someone can provide me a better one.. Please find the relevant c# code here.

No comments:

Post a Comment