Jump to content

Using DateTIme Comparison with while loop


eldan88
Go to solution Solved by mac_gyver,

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;
    }
   
 }
Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.