0

I want to generate an array of dates between two dates with an interval of 1 hour.

Inital date: 01-01-2013 00:00:00
Final date: 02-01-2013 00:00:00

ex. of result:

[01-01-2013 00:00:00, 01-01-2013 01:00:00, 01-01-2013 02:00:00, (...), 02-01-2013 00:00:00]
2

4 Answers 4

2

Try this

    $dates = array();
    $start = strtotime('01-01-2013 00:00:00');
    $end = strtotime('02-01-2013 00:00:00');
    for($i=$start;$i<$end;$i+=3600) {
        $dates[] = date('Y-m-d H:i:s',$i);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't you be better off using strtortime('+1 hour') over adding 3600 to the date every time? Since strtotime came out everywhere I've read has recommended using that over date.
2
$start = new DateTime('2013-07-01 00:00:00', new DateTimeZone('UTC'));
$interval = new DateInterval('PT1H');
$end = new DateTime('2013-07-03 00:00:00', new DateTimeZone('UTC'));

$period = new DatePeriod($start, $interval, $end);

foreach ($period as $date) {
    $dateArray[] = $date->format('Y-m-d h:i:s');
}
var_dump($dateArray);

1 Comment

IMHO this is the correct answer. I edited your code slightly as the OP asked for an array to be generated. +1.
1
<?php
$start = '2013-01-01 00:00:00';
$end   = '2013-01-02 00:00:00';

$dates = array();

$current = strtotime($start);

$offset = 0;
while ( $current < strtotime($end) ) {
    $current = strtotime("$start +{$offset} hours");
    $dates[] = date('d-m-Y H:i:s', $current); 
    $offset++;
}

print_r($dates);

Comments

0

You could try this.

$start = mktime(0,0,0,1,1,2013);
$end = mktime(0,0,0,2,1,2013);
$inc = 60*60; // 1 hour

for ($x=$start; $x<=$end; $x+$inc ) {
    $dates = date('d-m-Y H:i:s, $x);
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.