Search code examples
phpdatedayofweek

Get finish date, given start date and schedule in week


I have a problem using PHP to get the finish date of course, as below:

Inputs:

  • Start date (e.g: 8/23/2019)
  • Schedule in week (e.g: Monday, Tuesday, Friday)
  • Total of lessons (e.g: 8)

Output: The finish date of course (is 9/9/2019 with above e.g inputs).

One lesson is one day. Input fields from end user: Input fields from end user

Sorry for my bad English. Thank you very much!


Solution

  • As I see it loop while there are lessons left and subtract when it's Monday, Tuesday or Friday.
    After the loop output the date.

    $start = "8/23/2019";
    $days = ["Monday", "Tuesday", "Friday"];
    $n = 8;
    
    $d = strtotime($start);
    while($n>0){
        //See if day is in days array
        if(in_array(date("l", $d), $days)){
            $n--;
        }
        $d += 86400; // go to next day
    }
    
    echo date("m/d/Y", $d-86400); //-86400 because  the loop adds one at the end.