Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Create Timeslots with break timing using DatePeriod

I want to create time slots with start,end time & also break timing.

public function getServiceScheduleSlots($duration,$break, $stTime,$enTime)
{
    $start = new DateTime($stTime);
    $end = new DateTime($enTime);
    $interval = new DateInterval("PT" . $duration. "M");
    $period = new DatePeriod($start, $duration, $end);

    foreach ($period as $dt) {
        $periods[] = $dt->format('H:iA');
    }
    return $periods;
}

For ex.,
My service start time 10:00 AM , End Time 12:00 PM.
Condition: each service time 30 min & 15 min break.

Above method returns like,

  • 10:00 AM - 10:30 AM
  • 10:30 AM - 11:00 AM
  • 11:00 AM - 11:30 AM
  • 11:30 AM - 12:00 PM

Expected results as,

  • 10:00 AM - 10:30 AM
  • 10:45 AM - 11:15 AM
  • 11:30 AM - 12:00 PM

I want to add break time when each period starts.

Thanks in advance.

like image 770
ArivuAjay Avatar asked Jan 12 '23 16:01

ArivuAjay


1 Answers

How about this....

function getServiceScheduleSlots($duration,$break, $stTime,$enTime)
{
        $start = new DateTime($stTime);
        $end = new DateTime($enTime);
        $interval = new DateInterval("PT" . $duration. "M");
        $breakInterval = new DateInterval("PT" . $break. "M");

        for ($intStart = $start; 
             $intStart < $end; 
             $intStart->add($interval)->add($breakInterval)) {

               $endPeriod = clone $intStart;
               $endPeriod->add($interval);
               if ($endPeriod > $end) {
                 $endPeriod=$end;
               }
               $periods[] = $intStart->format('H:iA') . 
                            ' - ' . 
                            $endPeriod->format('H:iA');
        }

        return $periods;
  }
like image 185
Bob Vale Avatar answered Jan 16 '23 22:01

Bob Vale