一周中的时间可以用相对日期表达式保存在一个数组中。
$times = [
"Tue 18:30",
"Wed 18:30",
"Thu 19:30",
"Fri 19:30",
"Sat 14:00",
"Sat 19:30",
"Sun 15:00",
];
所有这些时间都被添加到 $curDate 中,并在检查后将这些值中的最小值保存为 $nextDate。
这将在一个 while 循环中继续,直到结束日期。我为此写了一个函数。
function schedulePeriod(array $times, $start, $end)
{
$period = [];
$curDate = clone $start;
while(true){
$nextDate = clone $end;
foreach($times as $modifier){
$nextTime = (clone $curDate)->modify($modifier);
if($nextTime > $curDate AND $nextTime < $nextDate){
$nextDate = $nextTime;
}
}
if($nextDate >= $end) break;
$period[] = $nextDate;
$curDate = $nextDate;
}
return $period;
}
这个函数的结果是一个日期时间对象的数组。
$start = date_create("2020-05-01 00:00");
$end = date_create("2020-06-01 00:00");
$period = schedulePeriod($times, $start, $end);
echo '<pre>';
var_export($period);
输出(减少):
array (
0 =>
DateTime::__set_state(array(
'date' => "2020-05-01 19:30:00.000000",
'timezone_type' => 3,
'timezone' => "Europe/Berlin",
)),
1 =>
DateTime::__set_state(array(
'date' => "2020-05-02 14:00:00.000000",
'timezone_type' => 3,
'timezone' => "Europe/Berlin",
)),
2 =>
DateTime::__set_state(array(
'date' => "2020-05-02 19:30:00.000000",
'timezone_type' => 3,
'timezone' => "Europe/Berlin",
)),
3 =>
DateTime::__set_state(array(
'date' => "2020-05-03 15:00:00.000000",
'timezone_type' => 3,
'timezone' => "Europe/Berlin",
)),
dateTime 格式方法可用于实现所需的日期格式。