2013-07-05 30 views
0

我想生成两个日期之间的数组,间隔为1小时。如何用php生成一个日期数组?

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

ex。结果:

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

检查这个http://stackoverflow.com/questions/4312439/php-return-all-dates-between-two-dates-in-an-array – Pradeeshnarayan

+0

的可能重复[数组与日期之间两个不同的日期](http://stackoverflow.com/questions/11451565/array-with-dates-between-two-different-dates) –

回答

2

试试这个

$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); 
    } 
+2

你不会更好使用'strtortime('+ 1小时')'每次增加3600到日期?由于'strtotime'出现在任何地方,我读过推荐使用'date'。 – Styphon

+0

它看起来很完美:)谢谢 – user1136575

0

你可以试试这个。

$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); 
} 
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); 
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

恕我直言,这是正确的答案。当OP要求生成一个数组时,我稍微编辑了你的代码。 +1。 – vascowhite