Albus One
Albus One

Reputation: 191

PHP show range of hours and ignore past time

I am trying to make a little script which shows range of hours between 11:00 and 17:00. 11:00 is start point and 17:00 is end point. So far i have made this:

<?php
// Defining hours
$now = "13:00"; // <- my time now
$start_time = "11:00"; // start point
$end_time = "17:00"; // end point

// Convert to timestamps
$begin = strtotime($start_time);
$end = strtotime($end_time);

// Display range
while($begin <= $end) {
    echo date("H:i", $begin)." </br />";
    $begin = strtotime('1 hour', $begin);
}
?>

And it successfully output of range between start and end points:

11:00 
12:00 
13:00 
14:00 
15:00 
16:00 
17:00 

My goal is to make this script show range of hours from 13:00 (my time) if actual time is more than start time (11:00). Something like this:

11:00 hidden
12:00 hidden
13:00 
14:00 
15:00 
16:00 
17:00 

Can someone suggest how to make it?

Upvotes: 0

Views: 59

Answers (3)

Passionate Coder
Passionate Coder

Reputation: 7294

In this case simply use this:

$present = strtotime($now);
if($present > $begin){  
    $begin  = $present;
}

but what you need if say $now = 18:00 or beyond this.

In this case this code show nothing.

Upvotes: 2

Albus One
Albus One

Reputation: 191

I have added small bits as @user1234 suggested and now it works as i wanted. Here is the full code for reference to others.

<?php
// Defining hours
$now = "13:00"; // <- my time now
$start_time = "11:00"; // start point
$end_time = "17:00"; // end point

// Convert to timestamps
$actual = strtotime($now);
$begin = strtotime($start_time);
$end = strtotime($end_time);

// Added this to see if actual time is more than start time - creadit user1234
if($actual > $begin) {  
    $begin = $actual;
}

// Added this to see if actual time is more than 17:00
if($actual > $end) {  
    echo "Try tomorrow";
}
// Display ranges accordingly.
while($begin <= $end) {
    echo date("H:i", $begin)." </br />";
    $begin = strtotime('1 hour', $begin);
}
?>

Anyone is welcome to test and use if needed.

Upvotes: 0

insertusernamehere
insertusernamehere

Reputation: 23580

I think you can simplify your whole solution. Instead of using time operations, why don't you simply increase a variable from current hour or 11 to 17. To determine $begin simply use max(), like this:

$begin = max(date('H'), 11);
$end = 17;

while($begin <= $end) {
    echo $begin . ':00<br>';
    $begin++;
}

Upvotes: 0

Related Questions