加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP使用DatePeriod创建具有中断时间的时间段

发布时间:2020-12-13 21:50:08 所属栏目:PHP教程 来源:网络整理
导读:我想用开始,结束时间和时间创建时隙.也打破时机. public function getServiceScheduleSlots($duration,$break,$stTime,$enTime){ $start = new DateTime($stTime); $end = new DateTime($enTime); $interval = new DateInterval("PT" . $duration. "M"); $pe
我想用开始,结束时间和时间创建时隙.也打破时机.

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

例如,
我的服务开始时间是上午10:00,结束时间中午12:00.
条件:每个服务时间30分钟&休息15分钟.

上面的方法返回如,

>上午10:00 – 上午10:30
>上午10:30 – 上午11:00
>上午11:00 – 上午11:30
>上午11:30 – 中午12:00

预期结果为,

>上午10:00 – 上午10:30
>上午10:45 – 上午11:15
>上午11:30 – 中午12:00

我想在每个时段开始时添加休息时间.

提前致谢.

解决方法

这个怎么样….

function getServiceScheduleSlots($duration,$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;
  }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读