Pathik Vejani Pathik Vejani - 2 months ago 7
PHP Question

print time between 10pm to 3am

I have 2 time strings as below:

10pm
3am


I want to print the time between above-given string like:

10pm
11pm
12am
1am
2am
3am


PHP Code I tried:

<?php
$new_otime = strtotime(date('H:i',strtotime('10pm')));
$close_time = strtotime(date('H:i',strtotime("3am")));
do { ?>
<option value="<?php echo date("g a",$new_otime) ?>"><?php echo date("g a",$new_otime); ?></option>
<?php
$new_otime = $new_otime+=3600;
} while ($new_otime == $close_time);
?>


But it echoes only 10 pm in the select box. How can I echo all the time between those string?

Answer

I suggest some work around to make this work:

<?php
$new_otime = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d').' 10pm')));
$close_time = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d').' 3am')));
if($close_time < $new_otime){
  $close_time = strtotime(date('Y-m-d H:i',strtotime(date('Y-m-d',strtotime('+1 day')).'3am')));
}
do { ?>
<option value="<?php echo date("g a",$new_otime) ?>"><?php echo date("g a",$new_otime); ?></option>
<?php
$new_otime = $new_otime+=3600;                      
} while ($new_otime <= $close_time);
?>
  1. Check if end time is bigger
  2. If not make it next day
  3. Loop while new_otime is less than close_time