PHP:以字符串形式返回两天之间的所有24小时格式小时

时间:2018-08-06 06:11:34

标签: php

如何在PHP中打印两个日期之间的所有时间? 预期: 上午01:00 上午02:00 。 。 下午21:00

2 个答案:

答案 0 :(得分:1)

尽管suresh答案在大多数情况下是正确的,但并不能涵盖所有问题。

在时区时,夏令时会变得很混乱。

考虑使用DateTimeDateInterval

$from = new DateTime("2018-01-10 10:00:00 UTC");
$to = new DateTime("2018-01-10 16:00:00 UTC");
$interval = new DateInterval("PT1H");

for ($now = clone $from; $now < $to; $now->add($interval)) {
    echo $now->format("Y-m-d H:i:s e  -->  H:i A") . "\n";
}

输出效果很好

2018-01-10 10:00:00 UTC  -->  10:00 AM
2018-01-10 11:00:00 UTC  -->  11:00 AM
2018-01-10 12:00:00 UTC  -->  12:00 PM
2018-01-10 13:00:00 UTC  -->  13:00 PM
2018-01-10 14:00:00 UTC  -->  14:00 PM
2018-01-10 15:00:00 UTC  -->  15:00 PM

但是此代码还将涵盖时间更改

$from = new DateTime("2018-03-24 20:00:00 Europe/Warsaw");
$to = new DateTime("2018-03-25 06:00:00 Europe/Warsaw");
$interval = new DateInterval("PT1H");

for ($now = clone $from; $now < $to; $now->add($interval)) {
    echo $now->format("Y-m-d H:i:s e  -->  H:i A") . "\n";
}
2018-03-24 20:00:00 Europe/Warsaw  -->  20:00 PM
2018-03-24 21:00:00 Europe/Warsaw  -->  21:00 PM
2018-03-24 22:00:00 Europe/Warsaw  -->  22:00 PM
2018-03-24 23:00:00 Europe/Warsaw  -->  23:00 PM
2018-03-25 00:00:00 Europe/Warsaw  -->  00:00 AM
2018-03-25 01:00:00 Europe/Warsaw  -->  01:00 AM
2018-03-25 03:00:00 Europe/Warsaw  -->  03:00 AM
2018-03-25 04:00:00 Europe/Warsaw  -->  04:00 AM
2018-03-25 05:00:00 Europe/Warsaw  -->  05:00 AM

请注意,由于我们已切换为夏季时间(CET到CEST时区),所以没有凌晨02:00

答案 1 :(得分:0)

尝试使用for循环,它将打印两个值之间的小时数

$a = '05:00';
$b = '10:00';

// convert the strings to unix timestamps
$a = strtotime($a);
$b = strtotime($b);

// loop over every hour (3600sec) between the two timestamps
for($i = 0; $i < $b - $a; $i += 3600) {
  // add the current iteration and echo it
  echo date('H:i', $a + $i).'<br>';
}

?>

输出:

    05:00
    06:00
    07:00
    08:00
    09:00
    10:00