Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

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

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

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

How can I do this with PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...