0

I'm using military time (0930, 1000, etc) for times. I have a start time and end time. I need to find the number of 15 minute increments between them, i.e 0900 to 1115 would be 8 blocks of 15, 1130 to 1430 would be 12 blocks of 15, etc. How can I do this with a for loop?

3 Answers3

4

I'd be looking at strtotime.

Is this not a dupe question? I mean really any time diff question probably covers this.

Something simple would be:

<?php
$timeStart = '11:30';
$timeStop = '13:30';

$diff = strtotime($timeStart) - strtotime($timeStop);
echo ABS($diff / 60 / 15); // the total number of minutes between the the two times divided by 15. 

Not sure how you might want to round the quotient.

ficuscr
  • 6,975
  • 2
  • 32
  • 52
  • @BostonPHPGuy if you cannot figure out how to add a colon and do the rest, i used ficuscr's solution adding a colon and rounding the result down https://3v4l.org/N9J6L – Nodir Rashidov May 11 '18 at 18:05
  • This code will work with or without `:`. More of concern is preceding zero . eg `0930` not `930`. Honestly, i'd create a fully defined datetime string. Then you'll accurately account for daylights savings and that stuff. – ficuscr May 11 '18 at 18:16
  • oh wow. I did not expect it to work without a colon! Thanks for letting me know – Nodir Rashidov May 11 '18 at 18:20
  • 1
    The `strtotime` function is pretty amazing when it comes to what it will parse. That said, better to be as explicit as possible to not get caught on some fringe case where ambiguity can enter (I'd probably format them with `:`, and full date parts). – ficuscr May 11 '18 at 18:21
0

You can use this method.
I convert the time to a decimal value and subtract.
Then just multiply with 4 since there is four quaters in one hour.

$start = "09:30";
$end = "11:15";

list($hour, $min) = explode(":",$start);
$start = $hour + round($min/60,2);

list($hour, $min) = explode(":",$end);
$end = $hour + round($min/60,2);

echo ($end-$start)*4;

https://3v4l.org/q566p

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

I've made an attempt to implement your answer by using for loop

function militaryTime($startTime,$endTime,$interval=15)
{
   $count = 0;
   for($i=00;$i<=23;$i++)
   {
        for($j=00;$j<=59;$j++)
        {
            if(strtotime($i.":".$j)>strtotime($startTime) && strtotime($i.":".$j)<strtotime($endTime))
            {
                if($j%$interval==0)
                {
                    //echo $i.":".$j."<br>";
                    $count++;
                }
            }
        }
    }
    return $count;
}
$countOfMins = militaryTime("09:00","11:15"); //call the above declared function and get Value.

When you run this it will generate the output as expected i.e. 8.