Ryan
Ryan

Reputation: 1

Generate a date schedule that executes only on weekdays

I have a date schedule function in PHP which aims to execute only on working days. The code I have at the moment is generating the schedule for all days of the week so the while statement doesn't seem to working and I'm not sure why.

I'm a student, so I'm not very experienced with this kind of thing. Here is the code I have so far:

public static function generate_date_schedule($tasksperdayschedule, $startdate) {
    $schedule = [];

    $date = clone $startdate;

    foreach ($tasksperdayschedule as $numberoftasks) {
        $day = (int)$date->format('N');

        // Skip weekend days.
        while ($day > 5) {
            $date->add(new DateInterval('P1D'));
            $day = (int)$date->format('N');
        }

        $schedule[$date->format(self::DATE_FORMAT)] = $numberoftasks;

        $date->add(new DateInterval('P1D'));
    }

   return $schedule;

It is probably something very small I am missing, but any help would be appreciated! Thanks

Upvotes: 0

Views: 279

Answers (1)

sidx
sidx

Reputation: 640

I think its a simple logical error.

Inside the while loop you're updating $day, but the foreach loop continues to execute the rest of the code.

Better yet, you can avoid the while loop by:

if($day > 5)
    continue;

Upvotes: 1

Related Questions