PHP创建日期范围 [英] PHP create range of dates

查看:134
本文介绍了PHP创建日期范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从以下格式开始的日期: 2011-05-01 09:00:00 ,如何创建一个包含所有办公时间的阵列(09:00至17:00)(所有星期六和星期日除外)。我想到达的是这样的:

Starting with a date in this format: 2011-05-01 09:00:00, how can I create an array that contains all office hours (09:00 to 17:00) for all working days of the year (so excluding all Saturday and Sundays). What I want to arrive to is something like this:

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

开始日期将是本月的第一个在09:00的时间,最后一个日期(数组的最后一个元素)将永远是一年的最后一天17:00。

The start date will be the first of the current month at with 09:00 as time and the very last date (last element of the array) will always be 17:00 on the last day of the year.

再次,周末应该被排除。

Again, weekends should be excluded.

伪代码想法:
我想到了一些类似 strtotime($ start,+1一小时),检查如果小于17:00,但似乎并不简单。

Pseudocode idea: I thought of something like strtotime($start, "+1 one hour") with a check for "if smaller than 17:00" but it doesn't seem to be that simple.

推荐答案

如何做:

$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);
    }
}

外循环遍历给定的所有日子时间段。在外圈,我们检查一下是星期六还是星期天(一个周末),如果是的话,我们跳过那一天。如果不是周末,我们会循环遍历所有有效的时间,并在阵列中添加完整的日期和时间。

The outer loop iterates through all the days in the given time period. In the outer loop, we check to see if the day is either Saturday or Sunday (a weekend), and if it is, we skip that day. If it's not a weekend, we loop through all the valid hours, adding the full date and time to the array as we go.

这篇关于PHP创建日期范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆