user1946891
user1946891

Reputation: 955

can't add time in a while loop

I'm trying to increment time in a while loop but it is failing. I need the start time to increment 20 minutes every loop as long as it is less than the end time. The results are then echo in a button as a choice for the user.

$SAM is start time stored in MySQL database as 07:00:00
$EAM is end time stored in MySQL database as 10:00:00

while(strtotime($SAM) < strtotime($EAM)){
    $SAM = new DateTime($SAM);
    $SAM = $SAM->format('g:i');
    $SAMEND = new DateTime($SAM);
    $SAMEND->modify('+20 minutes');
    $SAMENDF = $SAMEND->format('g:i');
    $SAM = new DateTime(strtotime($SAMEND));
    echo '<button style="margin:5px 0px" class="btn btn-primary btn-block">'.$SAM.' - '.$SAMENDF.'</button>';
}

Upvotes: 1

Views: 63

Answers (1)

Qirel
Qirel

Reputation: 26450

You're mixing a bit on objects and strings, in addition that strtotime() cannot take an object. You also seem to be doing it a bit more complicated than you need. If I understand it correctly, this is what you're looking for.

You can compare DateTimes directly, like $SAM < $EAM.

$SAM = new DateTime('07:00:00');
$EAM = new DateTime('10:00:00');

while ($SAM < $EAM) {
    $START = $SAM->format('g:i');      // The start value will be equal to the ending of the last one in the previous loop
    $SAM->modify('+20 minutes');       // Increase it for 20 minutes each loop
    $SAMEND = $SAM->format('g:i');     // This will be increased by 20 minutes in relation to $START
    echo '<button style="margin:5px 0px" class="btn btn-primary btn-block">'.$START.' - '.$SAMEND.'</button> ';
}

This will create an output with buttons like

[7:00 - 7:20] [7:20 - 7:40] [7:40 - 8:00]
[8:00 - 8:20] [8:20 - 8:40] [8:40 - 9:00]
[9:00 - 9:20] [9:20 - 9:40] [9:40 - 10:00]

Upvotes: 1

Related Questions