Jump to content

Using DateTIme Comparison with while loop


eldan88

Recommended Posts

Hey Guys. I am trying to out put a list of times in a while loop and break when it reaches the closing time. When I do a simple comparision it shows whether its true or false... How ever the comparison will not work in a while loop it will not work. I have tried every single method I can possibly think of and it just won't loop. Do you guys have any suggestions on how I can make this work??

 

Below is my code. Thanks!

<?php 
$date = new DateTime("now");
$date->setTimezone(new DateTimeZone("America/New_York"));
$date->setTime($date->format('G'), ceil($date->format('i') / 15) * 15); // Rounds the minutes to the nearest quarter of an hour. 
$closing_time = new DateTime("10:00");
 
 while($date > $closing_time) {
  echo $date->format('g:i a') ."<br>" ; // Only displays once 
   $date->modify( "+15 minutes" );
    if($date > $closing_time) {
     break;
    }
   
 }

Hey mac_gyver thank you so much for your response. I thought that if I pass the time zone, the parser will automatically know whether or not its AM or PM. I realized in order to calculate that dynamically I need to pass in the hour in the 24 hour format. That is what got me really confused. I went ahead and changed the whole format into  24 hour format. Instead of $date->format('g') (which is 12 hour format) i changed it to $date->('G') and instead of  passing $closing_time = new DateTime("10:00"); i passed in $closing_time = new DateTime("22:00");

 

Now it works.  I will copy and paste my code just in case anyone else is having this issue. Thank you once again!

<?php 
$date = new DateTime("now", new DateTimeZone("America/New_York"));
//Lined number 4 below
$date->setTime($date->format('G'), ceil($date->format('i') / 15) * 15); // Rounds the minutes to the nearest quarter of an hour. 

 $closing_time = new DateTime("22:00", new DateTimeZone("America/New_York"));

 while( $date < $closing_time  ) {
  echo $date->format('g:i a') ."<br>" ; // Only displays once 
   $date->modify( "+15 minutes" );
    if($date > $closing_time) {
     break;
   }
   
 }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.