Search code examples
phpdatediff

PHP DateDiff time range blocks


I have time range which is in blocks of 30 minutes,

13:00 - 13:30

13:30 - 14:00

14:00 - 14:30

15:00 - 15:30

etc...

I want select the correct 30 minute block by the current time.

e.g.

Current Time 13:42

13:00 - 13:30

13:30 - 14:00  <- This block is selected

14:00 - 14:30

15:00 - 15:30

The purpose is retrieve assign a value to that block.

Really what I'm asking if what method and approach would I use?

I'll be using PHP

Thanks

    $hour = date('H');
    $minutes = date('i');

    if ($minutes >= 30) 
    {
        $hour++;
    }


    echo $hour;


    /////////////////////

    echo "<BR>";


    $hour = date('H');
    $minute = (date('n')>30)?'30':'00';
    echo "$hour:$minute";

Solution

  • A simple string comparison after splitting with explode does it here:

    $blocks = [
    '12:30 - 13:00',
    '13:00 - 13:30',
    '13:30 - 14:00',
    '14:00 - 14:30'
    ];
    
    $curTime = '13:42';
    $found = false;
    foreach($blocks as $key => $block){
      $time = explode(' - ',$block);
      if($curTime >= $time[0] AND $curTime < $time[1]){
        $found = $key;
        break;
      }
    }
    if($found !== false) echo $blocks[$found];
    else echo 'not found';