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]
Baba
  • 94,024
  • 28
  • 166
  • 217
user1136575
  • 69
  • 1
  • 8
  • check this http://stackoverflow.com/questions/4312439/php-return-all-dates-between-two-dates-in-an-array – Pradeeshnarayan Jul 05 '13 at 10:23
  • possible duplicate of [array with dates between two different dates](http://stackoverflow.com/questions/11451565/array-with-dates-between-two-different-dates) – Rajeev Ranjan Jul 05 '13 at 10:25

4 Answers4

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);
    }
Nauphal
  • 6,194
  • 4
  • 27
  • 43
  • 2
    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`. – Styphon Jul 05 '13 at 10:25
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);
vascowhite
  • 18,120
  • 9
  • 61
  • 77
meze
  • 14,975
  • 4
  • 47
  • 52
  • 1
    IMHO this is the correct answer. I edited your code slightly as the OP asked for an array to be generated. +1. – vascowhite Jul 07 '13 at 05:28
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);
Matteo Riva
  • 24,728
  • 12
  • 72
  • 104
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);
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149