How can I make an array of times with half hour intervals?

后端 未结 9 1002
生来不讨喜
生来不讨喜 2020-12-06 02:27

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

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

How can I do this with PHP?

相关标签:
9条回答
  • 2020-12-06 03:03

    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;
    }
    
    0 讨论(0)
  • 2020-12-06 03:04

    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
    )
    
    0 讨论(0)
  • 2020-12-06 03:09

    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 讨论(0)
提交回复
热议问题