【问题标题】:PHP Howto generate timestamps in a timeframe with a specific weekly schedule?PHP如何在具有特定每周时间表的时间范围内生成时间戳?
【发布时间】:2020-08-09 19:01:42
【问题描述】:

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

每周时间表

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 获取时间范围内的所有星期二 - 每周时间表中的每个时间) 然后我可以合并数组并对其进行排序。

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

【问题讨论】:

    标签: php date timestamp schedule


    【解决方案1】:

    一周中的时间可以用相对日期表达式保存在一个数组中。

    $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 格式方法可用于实现所需的日期格式。

    【讨论】:

      猜你喜欢
      • 2022-01-06
      • 2017-07-13
      • 1970-01-01
      • 2023-01-28
      • 2018-04-14
      • 2020-12-20
      • 2012-08-25
      • 2018-12-28
      • 1970-01-01
      相关资源
      最近更新 更多