Php add 5 working days to current date excluding weekends (sat-sun) and excluding (multiple) holidays

前端 未结 3 1569
青春惊慌失措
青春惊慌失措 2021-02-11 11:23

For delivery of our webshop, we need to calculate 5 working days from the current date in php.

Our working days are from monday to friday and we have several closing day

3条回答
  •  清酒与你
    2021-02-11 12:14

    Based on Luke's answer:

    Difference is that this one generates holidays for every year

     25, 'month' => 12],//christimas
            ['day' => 1, 'month' => 1],//new year
            ['day' => 13, 'month' => 4]//easter
        ];
        /**
         * @param int $numBusinessDays
         * @param \DateTimeInterface $date
         * @return \DateTime
         */
        public static function getFutureBusinessDay(int $numBusinessDays, \DateTimeInterface $date)
        {
            $numBusinessDays = min($numBusinessDays, 1000);
            $businessDayCount = 0;
            $currentTimestamp = strtotime($date->format('Y-m-d'));
            $holidayDates = self::getHolidayDates();
            while ($businessDayCount < $numBusinessDays) {
                $next1WD = strtotime('+1 weekday', $currentTimestamp);
                $next1WDDate = date('Y-m-d', $next1WD);
                if (!in_array($next1WDDate, $holidayDates)) {
                    $businessDayCount++;
                }
                $currentTimestamp = $next1WD;
            }
            return (new \DateTime())->setTimestamp($currentTimestamp);
        }
    
        /**
         * @return array
         */
        private static function getHolidayDates()
        {
            $holidays = [];
            foreach (self::HOLIDAY_DATES as $holidayDate) {
                $date = new \DateTime();
                $date->setDate($date->format('Y'), $holidayDate['month'], $holidayDate['day']);
                $holidays[] = $date->format('Y-m-d');
            }
            return $holidays;
        }
    }
    

提交回复
热议问题