简体   繁体   English

PHP在两个日期范围之间的显示时间

[英]PHP display times between two date ranges

I am currently fiddling around with this PHP code which I modified to: 我目前正在摆弄我修改为的以下PHP代码:

$begin = new DateTime('2010-01-01 08:00');
$end = new DateTime( '2010-05-01 20:00');

$interval = DateInterval::createFromDateString('15 min');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt ) {
  echo $dt->format( "Y-d-m H:i" ) . '<br/>';
}

This echos: 这呼应:

2010-01-01 08:00
2010-01-01 08:15
2010-01-01 08:30
2010-01-01 08:45
2010-01-01 09:00
.....
2010-01-05 01:00
2010-01-05 01:15
2010-01-05 01:30
.....
2010-01-05 19:15
2010-01-05 19:30
2010-01-05 19:45

In the above code I want it only to out put the time between 8am and 8pm. 在上面的代码中,我只希望将时间设置为上午8点至晚上8点。 Any time between 8pm and 8 am shouddn't be displayed. 不应显示晚上8点至早上8点之间的任何时间。 I know essentially what I am doing wrong ie displaying a date range, but I would like to know how to solve it. 我本质上知道我在做什么错,即显示日期范围,但是我想知道如何解决它。

If you really need show the exact variable without filtering for some reasons, you can using 2 DatePeriod : 如果由于某些原因您确实需要显示确切的变量而不进行过滤,则可以使用2 DatePeriod:

<?php
$begin = new DateTime('2010-01-01 08:00');
$end = new DateTime( '2010-05-01 20:00');

$interval = new DateInterval('P1D');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt ) {
  $tempBegin = $dt;
  $tempEnd = clone $dt;
  $tempEnd->add(new DateInterval('PT12H1M')); //remove '1M' if you just need value 08.00 - 19.45
  if($tempEnd > $end)
    $tempEnd = $end;

  $tempInterval = new DateInterval('PT15M');
  $tempPeriod = new DatePeriod($tempBegin, $tempInterval, $tempEnd);

  foreach ( $tempPeriod as $temp ) {
    echo $temp->format( "Y-d-m H:i" ) . '<br/>';
  }
}

If you just need show or assign the value, @scrowler answer is what you need. 如果您只需要显示或分配值,@ scrowler的答案就是您所需要的。

You can do a string comparison on the maximum time and minimum time: 您可以对最长时间和最短时间进行字符串比较:

foreach ($period as $dt) {
    $hour_and_min = $dt->format('H:i');
    if($hour_and_min >= '08:00' && $hour_and_min <= '20:00') {
        echo $dt->format( "Y-d-m H:i" ) . '<br/>' . PHP_EOL;
    }
}

Example

Edit: your conditions of "between 8am and 8pm" and "between 8pm and 8am" are a little ambiguous as to whether you include 8am and 8pm in either of those statements... Adjust to suit by changing the less-than-or-equal-to and greater-than-or-equal-to operators to LT or GT: $hour_and_min > '08:00' && $hour_and_min < '20:00' 编辑: “在8am到8pm之间”和“在8pm到8am之间”的条件对于您是否在其中两个语句中都包括8am和8pm有点模棱两可...通过更改小于或-来进行调整以适合与LT或GT等于或大于或等于运算符: $hour_and_min > '08:00' && $hour_and_min < '20:00'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM