2

I have x.

x is minutes.

I have a string start_time like: 7:00

And I have a string end_time like: 14:00

how can print a list of time with increase x minutes for each loop?

I want print something like this:

if x = 30

7:00 - 7:30
7:30 - 8:00
...
13:30 - 14:00

I try do it with math functions in php like this:

$time = '7:00';
$mm = $hh = 0;
$str = explode(":",$time);
if(($str[1]+ $x) > 60)
{
...
}

but it there a more simple method? can date function in php do it?

Areza
  • 671
  • 14
  • 26
  • https://stackoverflow.com/questions/2767068/adding-30-minutes-to-time-formatted-as-hi-in-php – Naga Mar 09 '18 at 02:48

3 Answers3

3

You can use DatePeriod together with DateInterval to achieve this.

Create two DateTime intervals with your start and end times, and a DateInterval instance with the number of minutes you need. Then, create a DatePeriod with this information, and iterate over it to show the resulting times:

<?php
$minutes = 15;
$start = "07:00";
$end = "14:00";
$startDate = DateTime::createFromFormat("H:i", $start);
$endDate = DateTime::createFromFormat("H:i", $end);
$interval = new DateInterval("PT".$minutes."M");
$dateRange = new DatePeriod($startDate, $interval, $endDate);
foreach ($dateRange as $date) {
    echo $date->format("H:i")."<br>";
}

Demo

Result

07:00

07:15

07:30

07:45

08:00

08:15

08:30

08:45

09:00

09:15

09:30

09:45

10:00

10:15 // etc

ishegg
  • 9,685
  • 3
  • 16
  • 31
0

You can use the DatePeriod object along with a desired DateInterval object.

Example: https://3v4l.org/lg8QW

$start = new \DateTime('07:00');
$end = new \DateTime('14:00');
$interval = new \DateInterval('PT1M'); //change to desired interval
$periods = new \DatePeriod($start, $interval, $end);
foreach ($periods as $period) {
   echo $period->format('H:i') ;
}

Result:

07:00
07:01
07:02
07:03
07:04
07:05
07:06
07:07
07:08
07:09
07:10
07:11
07:12
07:13
07:14
07:15
07:16
07:17
07:18
07:19
07:20
//...
13:59
Will B.
  • 17,883
  • 4
  • 67
  • 69
0

You can use DateTime object.
just like this:

<?php

$start_time = '7:00';

$date1 = DateTime::createFromFormat('H:i', $start_time);
$old = $start_time;

while (true) {
    $date1->modify('+30 min');
    echo $old . '-' . $date1->format('H:i').PHP_EOL;

    $old = $date1->format('H:i');
    if ($old == '14:00')  {
        break;
    }
}

Output:

7:00-07:30
07:30-08:00
08:00-08:30
...
13:30-14:00

More info just see the manual here: DateTime

Codcodog
  • 11
  • 2