Home > OS >  How to I get a range of times from a start time and end times with an hour difference using PHP?
How to I get a range of times from a start time and end times with an hour difference using PHP?

Time:11-10

$course_hour = 1; $starttime = '07:00'; $endtime = '16:00';

I wish if it could return an array of values like below: If

$course_hour = 1;

$return_array = array('07:00 - 08:00', '08:00 - 09:00', '09:00 - 10:00', '10:00 - 11:00', '11:00 - 12:00', '12:00 - 13:00', '13:00 - 14:00', '14:00 - 15:00', '15:00 - 16:00'); If

$course_hour = 1.5;

$return_array = array('07:00 - 08:30', '8:30 - 10:00', '10:00 - 11:30', '11:30 - 13:00', '13:00 - 14:30', '14:30 - 16:00'); If

$course_hour = 2;

$return_array = array('07:00 - 09:00', '09:00 - 11:00', '11:00 - 13:00', '13:00 - 15:00');

function get_session_times($course_hour, $start_time, $end_time){
    if(strlen($start_time) < 5) $start_time = '0'.$start_time;
    if(strlen($end_time) < 5) $end_time = '0'.$end_time;
    $current_time = date("Y-m-d H:i");
    $session_starttime = date("Y-m-d H:i", strtotime(date("Y-m-d ").$start_time));
    $session_endtime = date("Y-m-d H:i", strtotime(date("Y-m-d ").$end_time));
    $session_starttime_ms = strtotime($session_starttime);
    $session_endtime_ms = strtotime($session_endtime);
    $session_times_array = array();
    for ($i = $session_starttime_ms; $i < $session_endtime_ms; ) { 
         $session_times_array[] = date("H:i", $i)."<br/>"; 
         $i = $i   ($course_hour * 60 * 60);
    }
    return $session_times_array;
}

CodePudding user response:

<?php 
$course_hour = 1.5; // 1 || 1.5 || 2
$starttime = '07:00';
$endtime = '16:00';
 
print_r(get_time_range($course_hour, $starttime, $endtime));

function get_time_range($course_hour, $starttime, $endtime){
  $to_add = '';
  switch($course_hour):
    case 1:
     $to_add = "  1 hours";
     break;
   case 1.5:
     $to_add = "  1 hours 30 minutes";
     break;
   case 2:
     $to_add = "  2 hours";
     break;
   default:
     $to_add = "  1 hours";
     break;
  endswitch;

 // get the total hours
 $from_time = strtotime($starttime); 
 $to_time = strtotime($endtime); 
 $diff_mins = round(abs($from_time - $to_time)/60);
 $diff_hours = $diff_mins/60;

 $hours_arr =[];

 for($i=1; $i<=$diff_hours; $i = $course_hour):

   $new_end_strtime = strtotime($starttime . $to_add);
   $endtime = date('H:i', $new_end_strtime);

   if($new_end_strtime <= $to_time): // checking the last end time is not greater than defined $endtime
     $str = $starttime . ' - '. $endtime;
     $tmp = strtotime($starttime . $to_add);
     $starttime = date('H:i', $tmp);
     array_push($hours_arr, $str);
   endif;

  endfor;

  return $hours_arr;
}
?>

CodePudding user response:

/**
 * Get session times from start to end.
 * 
 * @link https://stackoverflow.com/a/27497314/128761 Convert decimal to hour and minute.
 * @link https://stackoverflow.com/a/62064286/128761 Original source code for get session times.
 * @param int|float|double|decimal $course_hour Course hour.
 * @param string $start_time Start time. Format is Hour:minute HH:MM.
 * @param string $end_time End time.
 * @return array Return times in array.
 */
function getSessionTimes($course_hour, $start_time, $end_time): array
{
    if (!is_numeric($course_hour)) {
        return [];
    }
    if (empty($start_time) || empty($end_time)) {
        return [];
    }

    $courseHour = (int) $course_hour;
    $courseMinute = (fmod($course_hour, 1) * 60);

    $beginDate = new DateTime(date('Y-m-d') . ' ' . $start_time);
    $endDate = new DateTime(date('Y-m-d') . ' ' . $end_time);

    $result = [];
    while ($beginDate < $endDate) {
        $output = $beginDate->format('H:i') . ' - ';
        $beginDate->modify(' ' . $courseHour . 'hour ' . $courseMinute . 'minute');
        if ($beginDate > $endDate) {
            break;
        }
        $output .= $beginDate->format('H:i');
        $result[] = $output;
        unset($output);
    }

    unset($beginDate, $endDate);
    return $result;
}

You have to convert from decimal (for example 1, 1.5) to be hour and minute based on code from this answer.

And then I use code from this answer mentioned by mickmackusa to get times array.

Here is testing.

/**
 * This function is for test the result only. It is no need in your real project.
 */
function testResult($result, $expect)
{
    if (!is_array($result) || !is_array($expect)) {
        throw new Exception('The result and expect must be array.');
    }
    
    $totalResult = count($result);
    $totalExpect = count($expect);
    $totalTested = ($totalResult === $totalExpect);
    unset($totalResult, $totalExpect);

    foreach ($result as $index => $eachResult) {
        if (isset($expect[$index]) && $expect[$index] === $eachResult) {
            // matched.
        } else {
            throw new Exception('The result and expect at index ' . $index . ' does not matched. (' . $eachResult . ')');
        }
    }
    
    return $totalTested;
}

// run tests
$result = getSessionTimes(1, '07:00', '16:00');
$expect = ['07:00 - 08:00', '08:00 - 09:00', '09:00 - 10:00', '10:00 - 11:00', '11:00 - 12:00', '12:00 - 13:00', '13:00 - 14:00', '14:00 - 15:00', '15:00 - 16:00'];
print_r($result);
var_dump(testResult($result, $expect));

$result = getSessionTimes(1.5, '07:00', '16:00');
$expect = ['07:00 - 08:30', '08:30 - 10:00', '10:00 - 11:30', '11:30 - 13:00', '13:00 - 14:30', '14:30 - 16:00'];
print_r($result);
var_dump(testResult($result, $expect));

$result = getSessionTimes(2, '07:00', '16:00');
$expect = ['07:00 - 09:00', '09:00 - 11:00', '11:00 - 13:00', '13:00 - 15:00'];
print_r($result);
var_dump(testResult($result, $expect));

The result will be...

Array ( [0] => 07:00 - 08:00 [1] => 08:00 - 09:00 [2] => 09:00 - 10:00 [3] => 10:00 - 11:00 [4] => 11:00 - 12:00 [5] => 12:00 - 13:00 [6] => 13:00 - 14:00 [7] => 14:00 - 15:00 [8] => 15:00 - 16:00 )
boolean true

Array ( [0] => 07:00 - 08:30 [1] => 08:30 - 10:00 [2] => 10:00 - 11:30 [3] => 11:30 - 13:00 [4] => 13:00 - 14:30 [5] => 14:30 - 16:00 )
boolean true

Array ( [0] => 07:00 - 09:00 [1] => 09:00 - 11:00 [2] => 11:00 - 13:00 [3] => 13:00 - 15:00 )
boolean true

  • Related