PHP 如何在具有特定每周计划的时间范围内生成时间戳?

PHP Howto generate timestamps in a timeframe with a specific weekly schedule?

我必须找到一种在两个日期之间生成时间戳的方法,并严格遵守每周时间表。 (见下面的例子)

每周时间表

Mo - skip
Tu - 18.30
We - 18.30
Th - 19.30
Fr - 19.30
Sa - 14.00 & 19.30
So - 15.00

我想生成 2020-05-01 和 2020-05-31 之间的所有时间戳。

我的想法是使用 DatePeriod 从设定的时间范围内的每一天的时间生成所有时间戳。 (从开始日期获取第一个星期二,添加时间并使用 DatePeriod 获取时间范围内的所有星期二 - 每周时间表中的每个时间) 然后我可以合并数组并对其进行排序。

我想知道是否有更简单的方法来做到这一点?有什么想法吗?

星期几可以用相对日期表达式保存在数组中。

$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",
  )),

日期时间格式化方法可用于实现所需的日期格式。