Home  >  Q&A  >  body text

How to get a series of times from a start time and an end time, each one hour apart using PHP?

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

I want it to return an array of values ​​like this: 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');< /p>

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;
}

P粉994092873P粉994092873228 days ago369

reply all(2)I'll reply

  • P粉609866533

    P粉6098665332024-03-29 00:59:39

    <?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;
    }
    ?>

    reply
    0
  • P粉294954447

    P粉2949544472024-03-29 00:18:01

    /**
     * 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 must convert to hours and minutes according to 1, 1.5). com/a/27497314/128761">This answer.

    Then I used the code in this answer mentioned by mickmackusa to get the time array.

    This is a test.

    /**
     * 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...

    reply
    0
  • Cancelreply