PHP Create Timeslots with break timing using DatePeriod

家住魔仙堡 提交于 2019-12-10 09:32:48

问题


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.


回答1:


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;
  }


来源:https://stackoverflow.com/questions/20606770/php-create-timeslots-with-break-timing-using-dateperiod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!