PHP 创建日期范围

ste*_*tef 3 php datetime date-arithmetic

从以下格式的日期开始:2011-05-01 09:00:00,如何创建一个数组,其中包含一年中所有工作日(因此不包括所有星期六和星期日)的所有办公时间(09:00 到 17:00)。我想要到达的是这样的:

2011-05-01 09:00:00
2011-05-01 10:00:00
2011-05-01 11:00:00
2011-05-01 12:00:00
2011-05-01 13:00:00
2011-05-01 14:00:00
2011-05-01 15:00:00
2011-05-01 16:00:00
2011-05-01 17:00:00
//next day, starting at 09:00 and ending at 17:00
2011-05-02 09:00:00
...
2011-05-02 17:00:00
//until the last day of the year from 09:00 to 17:00
2011-12-31 09:00:00
...
2011-12-31 17:00:00
Run Code Online (Sandbox Code Playgroud)

开始日期将是当月的第一天,时间为 09:00,最后一个日期(数组的最后一个元素)将始终是一年中最后一天的 17:00。

同样,周末应该被排除在外。

伪代码想法: 我想到了类似strtotime($start, "+1 one hour")检查的东西,"if smaller than 17:00"但似乎没有那么简单。

Jim*_*zuk 5

这个怎么样:

$start = strtotime('2011-05-01');
$end = strtotime('2011-12-31');

$times = array();

for ($i = $start; $i <= $end; $i += 24 * 3600)
{
    if (date("D", $i) == "Sun" || date("D", $i) == "Sat")
    {
        continue;
    }

    for ($j = 9; $j <= 17; $j++)
    {
        $times []= date("Y-m-d $j:00:00", $i);
    }
}
Run Code Online (Sandbox Code Playgroud)

外循环遍历给定时间段内的所有日子。在外循环中,我们检查这一天是星期六还是星期日(周末),如果是,我们跳过那一天。如果不是周末,我们会遍历所有有效时间,并在执行过程中将完整的日期和时间添加到数组中。