14

I needed a list of times like so in an array...

12am
12:30am
1:00pm
...

How can I do this with PHP?

9 Answers 9

37

Here's an improved version of Alex's function that uses seconds for more precision:

function hoursRange( $lower = 0, $upper = 86400, $step = 3600, $format = '' ) {
    $times = array();

    if ( empty( $format ) ) {
        $format = 'g:i a';
    }

    foreach ( range( $lower, $upper, $step ) as $increment ) {
        $increment = gmdate( 'H:i', $increment );

        list( $hour, $minutes ) = explode( ':', $increment );

        $date = new DateTime( $hour . ':' . $minutes );

        $times[(string) $increment] = $date->format( $format );
    }

    return $times;
}

So, to make an array of times with 1-hour intervals over a 24-hour time period, use the defaults:

hoursRange();

Which will give you the following:

Array
(
    [00:00] => 12:00 am
    [01:00] => 1:00 am
    [02:00] => 2:00 am
    [03:00] => 3:00 am
    [04:00] => 4:00 am
    [05:00] => 5:00 am
    [06:00] => 6:00 am
    [07:00] => 7:00 am
    [08:00] => 8:00 am
    [09:00] => 9:00 am
    [10:00] => 10:00 am
    [11:00] => 11:00 am
    [12:00] => 12:00 pm
    [13:00] => 1:00 pm
    [14:00] => 2:00 pm
    [15:00] => 3:00 pm
    [16:00] => 4:00 pm
    [17:00] => 5:00 pm
    [18:00] => 6:00 pm
    [19:00] => 7:00 pm
    [20:00] => 8:00 pm
    [21:00] => 9:00 pm
    [22:00] => 10:00 pm
    [23:00] => 11:00 pm
)

Here are a few example uses:

// Every 15 Minutes, All Day Long
$range = hoursRange( 0, 86400, 60 * 15 );

// Every 30 Minutes from 8 AM - 5 PM, using Custom Time Format
$range = hoursRange( 28800, 61200, 60 * 30, 'h:i a' );

You can view a working snippet at CodePad.

4
  • 1
    Looks good - just not sure why you're exploding the $increment rather than passing it straight into DateTime constructor? Oct 21, 2015 at 17:26
  • Also, you could remove the if (format) and pass that default variable in the function. Jul 28, 2020 at 23:57
  • This might be handy to add. It converts a time string to seconds /** * Takes hour:minutes:seconds (8:15:00) OR minutes:seconds (15:00) * @param string $time * @return int */ function timeToSeconds(string $time): int { $timeParts = explode(':', $time); return 3 === count($timeParts) ? $timeParts[0] * 3600 + $timeParts[1] * 60 + $timeParts[2] : $timeParts[0] * 60 + $timeParts[1]; }
    – spoofie
    Nov 23, 2021 at 10:12
  • Thanks a lot @rjb rjb for saving my life :)
    – Kamlesh
    Jan 3 at 13:06
12

Thank-you for reopening the question alex.

This is a solution that should resonate with functional programmers.

function halfHourTimes() {
  $formatter = function ($time) {
    if ($time % 3600 == 0) {
      return date('ga', $time);
    } else {
      return date('g:ia', $time);
    }
  };
  $halfHourSteps = range(0, 47*1800, 1800);
  return array_map($formatter, $halfHourSteps);
}
1
  • Nice solution! I assume it needs PHP 5.3 with the function assigned to a variable? +1 (no worries on re opening, if I knew you were hard at work solving I would never have deleted it).
    – alex
    Oct 11, 2010 at 23:22
11

I decided this one was better :)

function hoursRange($lower = 0, $upper = 23, $step = 1, $format = NULL) {

    if ($format === NULL) {
        $format = 'g:ia'; // 9:30pm
    }
    $times = array();
    foreach(range($lower, $upper, $step) as $increment) {
        $increment = number_format($increment, 2);
        list($hour, $minutes) = explode('.', $increment);
        $date = new DateTime($hour . ':' . $minutes * .6);
        $times[(string) $increment] = $date->format($format);
    }
    return $times;
}
3

We can simply use strtotime to increment our time by N amount here in this case 30 minutes and date function to format it to our desired output.

$startTime = strtotime('12 am');
$endTime   = strtotime('11:59 pm');

$arrInterval = [];
while($endTime >= $startTime){
  $arrInterval[] = date("h:ia", $startTime);
  $startTime = strtotime('+30 minutes', $startTime);
}
1

Here is my suggestion :

    $start = new \DateTime('00:00');
    $times = 24 * 2; // 24 hours * 30 mins in an hour

    for ($i = 0; $i < $times-1; $i++) {
        $result[] = $start->add(new \DateInterval('PT30M'))->format('H:i A');
    }

    print_r($result);

Hope this help.

0

This is maybe a more elegant way, but it requires the times to be in seconds (that also makes it more flexible).

function time_range( $start, $end, $step = 1800 ) {
    $return = array();
    for( $time = $start; $time <= $end; $time += $step )
        $return[] = date( 'g:ia', $time );
    return $return;
}
0

Simplest solution

$h = 0;
while ($h < 24) {
    $key = date('H:i', strtotime(date('Y-m-d') . ' + ' . $h . ' hours'));
    $value = date('h:i A', strtotime(date('Y-m-d') . ' + ' . $h . ' hours'));
    $formatter[$key] = $value;
    $h++;
}

Result are:

Array
(
    [00:00] => 12:00 AM
    [01:00] => 01:00 AM
    [02:00] => 02:00 AM
    [03:00] => 03:00 AM
    [04:00] => 04:00 AM
    [05:00] => 05:00 AM
    [06:00] => 06:00 AM
    [07:00] => 07:00 AM
    [08:00] => 08:00 AM
    [09:00] => 09:00 AM
    [10:00] => 10:00 AM
    [11:00] => 11:00 AM
    [12:00] => 12:00 PM
    [13:00] => 01:00 PM
    [14:00] => 02:00 PM
    [15:00] => 03:00 PM
    [16:00] => 04:00 PM
    [17:00] => 05:00 PM
    [18:00] => 06:00 PM
    [19:00] => 07:00 PM
    [20:00] => 08:00 PM
    [21:00] => 09:00 PM
    [22:00] => 10:00 PM
    [23:00] => 11:00 PM
)
0

Here's a more flexible version that doesn't need DateTime (since we're already working with timestamps in seconds anyway). ;-)

function get_hours_range( $start = 0, $end = 86400, $step = 3600, $format = 'g:i a' ) {
        $times = array();
        foreach ( range( $start, $end, $step ) as $timestamp ) {
                $hour_mins = gmdate( 'H:i', $timestamp );
                if ( ! empty( $format ) )
                        $times[$hour_mins] = gmdate( $format, $timestamp );
                else $times[$hour_mins] = $hour_mins;
        }
        return $times;
}
-1

Added index value as hour:

Here is the code:

<?php

    $time_slot= array();
        
        if ( empty( $format ) ) {
            $format = 'H:i';
        }
        $lower = 0; $upper = 86400; $step = 3600; $format = '';
        $i = 0;
        foreach ( range( $lower, $upper, $step ) as $increment ) {
            $increment = gmdate( 'H:i', $increment );
           
        
             
            $time_slot[$i] = $increment;
            $i++;
        }
    
        print_r($time_slot);

?>

Here is the result:

Array
(
    [0] => 00:00
    [1] => 01:00
    [2] => 02:00
    [3] => 03:00
    [4] => 04:00
    [5] => 05:00
    [6] => 06:00
    [7] => 07:00
    [8] => 08:00
    [9] => 09:00
    [10] => 10:00
    [11] => 11:00
    [12] => 12:00
    [13] => 13:00
    [14] => 14:00
    [15] => 15:00
    [16] => 16:00
    [17] => 17:00
    [18] => 18:00
    [19] => 19:00
    [20] => 20:00
    [21] => 21:00
    [22] => 22:00
    [23] => 23:00
    [24] => 00:00
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.