填充时间范围晚上时间php


populate time range night times php

我有一个开放时间和一个关闭时间。使用这两个变量,我使用以下代码填充间隔为30分钟的时间范围:

function getTimeRange($open,$closed) {
  //$begin = new DateTime($open);
  $begin = new DateTime($open);
  $end   = new DateTime($closed);
  $interval = DateInterval::createFromDateString('30 min');
  $times    = new DatePeriod($begin, $interval, $end);
  $timeRange = [];
  foreach ($times as $time) {
    $timeRange[] = $time->add($interval)->format('H:i');
  }
  return $timeRange;
}

它工作良好,但有时我的开放时间是在晚上。从10点到3点。我这样做是为了让我的软件明白,如果一家商店开到2点,它就会把当天设置为前一天……如果是周一下午三点到两点…凌晨2点还是星期一。

但是现在对于这个时间范围的代码,我也需要这样的东西,但我不知道如何接近这个。因为当你输入open: 10:00 close: 23:59时,它工作得很好,但是当你将结束时间更改为2:00时,它什么也不做

如果结束时间是…00:00到04:00我想创建一个范围,并将其视为1天

//更新后的MAGUS AWNSER硬编码不起作用。但是在类中,我删除了顶部的"命名空间Carbon;"。然后一切都工作了,你的代码也很棒!

,但现在我得到错误;

Warning: The use statement with non-compound name 'DateTime' has no effect in /Applications/XAMPP/xamppfiles/htdocs/r/classes/class.Carbon.php on line 14
Warning: The use statement with non-compound name 'DateTimeZone' has no effect in /Applications/XAMPP/xamppfiles/htdocs/r/classes/class.Carbon.php on line 15
Warning: The use statement with non-compound name 'InvalidArgumentException' has no effect in /Applications/XAMPP/xamppfiles/htdocs/r/classes/class.Carbon.php on line 16
我不知道这是什么意思…如果我也注释掉:
//namespace Carbon;
//use DateTime;
//use DateTimeZone;
//use InvalidArgumentException;

then all works no error…所以我不知道这是否会引起问题?

我建议你使用碳!https://github.com/briannesbitt/Carbon

你的函数看起来像这样:

<?php
function getTimeRange($open,$closed) {
    $begin = Carbon::createFromFormat('H:i', $open); //assuming 20:00 here
    $end   = Carbon::createFromFormat('H:i', $closed); //assuming 04:00 here
    //Checking if $closed is in the same day!
    if(intval(explode(':',$open)[0]) > intval(explode(':',$closed)[0]){
        //Truth means that 20 > 4, so $closed should be the next day!
        $end->addDay();
    }
    //I didnt really understood what you wanted here but im guessing
    //you want some sort of array like ['20:00','20:30','21:00',...]
    $halfTimes = $begin->diffInHours($end) * 2;
    $timeRange = [];
    for($i=0;$i<$halfTimes;$i++){
        $begin->addMinutes(30);
        $timeRange[] = $begin->format('H:i');
    }
    return $timeRange;
}