PHP 创建日期范围

发布于 2024-11-09 10:21:40 字数 761 浏览 0 评论 0原文

从以下格式的日期开始: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

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

再次强调,周末应该被排除在外。

伪代码想法: 我想到了类似 strtotime($start, "+1 one hour") 的东西,并检查 "if less than 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

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

梦萦几度 2024-11-16 10:21:40

怎么样:

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

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

How about this:

$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.

望她远 2024-11-16 10:21:40

一些提示:

  1. date("G", $some_timestamp) 以 24 小时格式提供一天中的小时
  2. date("N", $some_timestamp) 为您提供一周中的某一天,1(周一)到 7(周日)

查看 PHP 手册日期

编辑:您可以选择任何开始时间戳并添加 3600 以添加一小时,如果您的小时大于 17,您可以添加更大的步长以直接到第二天早上,周末也是如此,只需执行 while ($timestamp < $end_timestamp) {}

Some tips:

  1. date("G", $some_timestamp) gives you the hour of the day in 24-hour format
  2. date("N", $some_timestamp) gives you the day of the week, 1 (for Monday) through 7 (for Sunday)

Take a look at the php manual for date.

Edit: You can pick any start timestamp and add 3600 to add one hour, if your hour is greater than 17, you can add a bigger step to go right to the next morning, same for a weekend, and just do a while ($timestamp < $end_timestamp) {}

北座城市 2024-11-16 10:21:40

我鼓励您使用精彩的 DateTime 类及其相关类。在这里,你可以充分利用DatePeriod

<?php

$now = new DateTime('today'); // starting time 0.00 this morning
$endOfYear = new DateTime('31 December this year 23:00'); // end time
$interval = new DateInterval('PT1H'); // frequency -- every hour

$times = array();

foreach (new DatePeriod($now, $interval, $endOfYear ) as $datetime) {
// $datetime is a DateTime object for the hour and time in question
    $dow = $datetime->format('w'); // 0 is Sunday
    if (($dow == '0') || ($dow == '6')) {
        continue; // miss Saturday and Sunday out
    }

    $time = $datetime->format('G'); // hour without leading 0
    if (($time < '9') || ($time > '17')) {
        continue;
    }

    $times[] = $datetime->format('r'); // output format
}

var_dump($times);

显然,您可以配置各个方面,尤其是输出格式。根据您的目的,您可能更愿意将 DateTime 对象本身放入数组中。

I'd encourage you to use the wonderful DateTime class and its related classes. Here, you can make good use of DatePeriod:

<?php

$now = new DateTime('today'); // starting time 0.00 this morning
$endOfYear = new DateTime('31 December this year 23:00'); // end time
$interval = new DateInterval('PT1H'); // frequency -- every hour

$times = array();

foreach (new DatePeriod($now, $interval, $endOfYear ) as $datetime) {
// $datetime is a DateTime object for the hour and time in question
    $dow = $datetime->format('w'); // 0 is Sunday
    if (($dow == '0') || ($dow == '6')) {
        continue; // miss Saturday and Sunday out
    }

    $time = $datetime->format('G'); // hour without leading 0
    if (($time < '9') || ($time > '17')) {
        continue;
    }

    $times[] = $datetime->format('r'); // output format
}

var_dump($times);

Obviously there are various aspects of this that you can configure, especially the output format. Depending on your purpose, you may prefer to put the DateTime objects themselves into the array.

心在旅行 2024-11-16 10:21:40
$datetime = new DateTime(); // Set your start date here
do { // Iterate over .. dont know, a long time?
  do { // Iterate over the week ...
    $datetime->setTime(9,0,0);
    do { // Iterate over the hours ...
      echo $datetime->format('c') . PHP_EOL; // Do something with $datetime here
      $datetime->add(new DateInterval('PT1H'));
    } while ($datetime->format('G') < 18); // .. till < 18
    $datetime->add(new DateInterval('P1D')); // next day
  } while (!in_array($datetime->format('w'), array('0','6'))); // until we hit sunday or saturday
  $datetime->add(new DateInterval('P2D')); // next monday
} while (true); // replace with your "end" expression

目前未经测试。

您也可以使用常见的间隔字符串(例如 1 小时 等)http:// /php.net/dateinterval.createfromdatestring

$datetime = new DateTime(); // Set your start date here
do { // Iterate over .. dont know, a long time?
  do { // Iterate over the week ...
    $datetime->setTime(9,0,0);
    do { // Iterate over the hours ...
      echo $datetime->format('c') . PHP_EOL; // Do something with $datetime here
      $datetime->add(new DateInterval('PT1H'));
    } while ($datetime->format('G') < 18); // .. till < 18
    $datetime->add(new DateInterval('P1D')); // next day
  } while (!in_array($datetime->format('w'), array('0','6'))); // until we hit sunday or saturday
  $datetime->add(new DateInterval('P2D')); // next monday
} while (true); // replace with your "end" expression

Currently untested.

You can use the common interval-strings (like 1 hour and so on) too http://php.net/dateinterval.createfromdatestring

剩一世无双 2024-11-16 10:21:40

您可以使用两个嵌套循环计算日期并使用 date() 生成字符串。

You could calculate your dates with two nested loops and generate the string with date().

装迷糊 2024-11-16 10:21:40

我将循环遍历从现在到年底的所有日期,按小时递增,如下所示(显然是伪代码):

for n = now until end of year
    if (date(n) is between 9:00 and 17:00) AND (if date(n) is not sat or sun)
        add to array
    end if
    increment n by 1 hour
end

I would just loop through all dates, incremented by hour, from now until the end of the year, as follows (pseudocode, obviously):

for n = now until end of year
    if (date(n) is between 9:00 and 17:00) AND (if date(n) is not sat or sun)
        add to array
    end if
    increment n by 1 hour
end
つ低調成傷 2024-11-16 10:21:40

这是一个应该相当快的解决方案,因为它不使用字符串比较并且循环内只有两个函数调用:

function hours()
{
    $start = mktime(0, 0, 0, date('n'), 1, date('Y'));
    $end = mktime(0, 0, 0, 1, 1, date('Y') + 1);
    $wday = date('w', $start);
    $result = array();
    for ($t = $start; $t < $end; $t += 3600 * 24) {
        if (($wday > 0) && ($wday < 6)) {
            for ($hour = 9; $hour <= 17; $hour++) {
                $result[] = date('Y-m-d', $t) . sprintf(' %02d:00:00', $hour);
            }
        }
        $wday = ($wday + 1) % 7;
    }
    return $result;
}

Here is a solution which should be reasonably fast since it uses no string comparisons and has only two function calls inside the loops:

function hours()
{
    $start = mktime(0, 0, 0, date('n'), 1, date('Y'));
    $end = mktime(0, 0, 0, 1, 1, date('Y') + 1);
    $wday = date('w', $start);
    $result = array();
    for ($t = $start; $t < $end; $t += 3600 * 24) {
        if (($wday > 0) && ($wday < 6)) {
            for ($hour = 9; $hour <= 17; $hour++) {
                $result[] = date('Y-m-d', $t) . sprintf(' %02d:00:00', $hour);
            }
        }
        $wday = ($wday + 1) % 7;
    }
    return $result;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文