Calculate an expected delivery date (accounting for holidays) in business days using JavaScript?

后端 未结 8 1574
悲&欢浪女
悲&欢浪女 2020-12-16 05:04

After revisiting this script, and some modifications, the following is available to allow a user to add a feature that calculates the expected delivery date.



        
8条回答
  •  自闭症患者
    2020-12-16 05:33

    We have UI that defaults search inputs to last business day or a week-ago. Here's something that works both forward and backward.

    // add (or subtract) business days to provided date
    addBusinessDays = function (startingDate, daysToAdjust) {
        var newDate = new Date(startingDate.valueOf()),
            businessDaysLeft,
            isWeekend,
            direction;
    
        // Timezones are scary, let's work with whole-days only
        if (daysToAdjust !== parseInt(daysToAdjust, 10)) {
            throw new TypeError('addBusinessDays can only adjust by whole days');
        }
    
        // short-circuit no work; make direction assignment simpler
        if (daysToAdjust === 0) {
            return startingDate;
        }
        direction = daysToAdjust > 0 ? 1 : -1;
    
        // Move the date in the correct direction
        // but only count business days toward movement
        businessDaysLeft = Math.abs(daysToAdjust);
        while (businessDaysLeft) {
            newDate.setDate(newDate.getDate() + direction);
            isWeekend = newDate.getDay() in {0: 'Sunday', 6: 'Saturday'};
            if (!isWeekend) {
                businessDaysLeft--;
            }
        }
        return newDate;
    };
    

    It would be easy to pass in an optional holidays data structure and adjust for that as well.

    However, generating a holidays data structure, well, that will take a little more effort and is specific not only to every country and region, but also to every organization.

提交回复
热议问题