简体   繁体   English

需要帮助以1小时为增量显示时间列表

[英]Need help displaying a list of time in 1 hour increments

I have wrote some code that should output a list of times starting from 6:00am to 23:45pm. 我写了一些代码,应该输出从6:00 am到23:45 pm的时间列表。

I am using the DateTime class to accomplish this. 我正在使用DateTime类来完成此操作。 The problem that I am running into, is that the while loop is an infinite while loop. 我遇到的问题是while循环是一个无限的while循环。 It doesn't stop. 它并没有停止。

I am having a really hard time understanding why it doesn't stop when I the condition is set to this.. \\ while ($formatted_start_time <= $end_hour){ 我很难理解为什么当我将条件设置为此时它不会停止.. \\ while ($formatted_start_time <= $end_hour){

Anyhow I would really appreciate it if someone can help me out. 无论如何,如果有人可以帮助我,我将非常感激。 Thank a lot. 非常感谢。

Below is the code that I have so far.. 下面是我到目前为止的代码。

 $start_hour = new DateTime("now",new DateTimeZone("America/New_York"));
 $start_hour->setTime(6,00);
 $formatted_start_time = $start_hour->format("H:i:s");


    $end_hour = mktime(23,45);

 while ($formatted_start_time <= $end_hour){
    $start_hour->modify("+60 minutes");
    $formatted_start_time = $start_hour->format("H:i:s");
     echo $formatted_start_time;

 }

This is easy, and readable, using DateInterval() and DatePeriod() : 使用DateInterval()DatePeriod() ,这很容易DatePeriod()

$start_hour = new DateTime('06:00', new DateTimeZone("America/New_York"));
// Add one minute as the loop is NOT inclusive
$end_hour   = new DateTime('23:46', new DateTimeZone("America/New_York"));
$interval   = new DateInterval('PT15M');
$period     = new DatePeriod($start_hour, $interval, $end_hour);
foreach ($period as $time) {
    echo $time->format('H:i:s');
}

Demo 演示版

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

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