我在PHP中有两个日期和时间:
$date1 = 2014-07-19 13:00
$date2 = 2014-07-20 13:00
我想要的是array of date and time
介于两个日期和时间之间,包括给定的日期。
喜欢 2014-07-19 13:00,2014-07-19 14:00,2014-07-19 15:00,... 2014-07-20 11:00,2014-07- 20 12:00,2014-07-20 13:00
当我搜索时,我找到了代码来获取两个日期之间的日期。但它不包括时间。我也想要时间。
答案 0 :(得分:2)
使用DatePeriod
$daterange = new DatePeriod(
new DateTime('2014-07-19 13:00'),
new DateInterval('PT1H'),
new DateTime('2014-07-20 13:00')
);
//if you just need to iterate
foreach($daterange as $date) {
print $date->format('Y-m-d H:i') . "\n";
}
//if you need an actual array
$dateArray = iterator_to_array($daterange);
print_r($dateArray);
答案 1 :(得分:1)
这对你有用:
<?php
$date1 = date_create('2014-07-19 13:00');
$date2 = date_create('2014-07-20 13:00');
$newArr = array();
// if start date is to be included then use
$newArr[] = date_format($date1, 'Y-m-d H:i:s');
while($date1 < $date2) {
$date1 = date_add($date1,date_interval_create_from_date_string('1 hour'));
$newArr[] = date_format($date1, 'Y-m-d H:i:s');
}
echo "<pre>";
print_r($newArr);
echo "</pre>";
和here是演示的小提琴
输出:
Array
(
[0] => 2014-07-19 13:00:00
[1] => 2014-07-19 14:00:00
[2] => 2014-07-19 15:00:00
[3] => 2014-07-19 16:00:00
[4] => 2014-07-19 17:00:00
[5] => 2014-07-19 18:00:00
[6] => 2014-07-19 19:00:00
[7] => 2014-07-19 20:00:00
[8] => 2014-07-19 21:00:00
[9] => 2014-07-19 22:00:00
[10] => 2014-07-19 23:00:00
[11] => 2014-07-20 00:00:00
[12] => 2014-07-20 01:00:00
[13] => 2014-07-20 02:00:00
[14] => 2014-07-20 03:00:00
[15] => 2014-07-20 04:00:00
[16] => 2014-07-20 05:00:00
[17] => 2014-07-20 06:00:00
[18] => 2014-07-20 07:00:00
[19] => 2014-07-20 08:00:00
[20] => 2014-07-20 09:00:00
[21] => 2014-07-20 10:00:00
[22] => 2014-07-20 11:00:00
[23] => 2014-07-20 12:00:00
[24] => 2014-07-20 13:00:00
)
答案 2 :(得分:1)
您可以使用PHP的range()功能:
$date1 = '2014-07-19 13:00';
$date2 = '2014-07-20 13:00';
$date_range = range(strtotime($date1), strtotime($date2), 3600);
foreach ($date_range as $k=>$a)
$date_range[$k] = date('Y-m-d H:i:s', $a);
print_r($date_range);
答案 3 :(得分:0)
$newdate = $date1;
$dates = array();
$dates[] = $next;
while(strtotime($newdate) < strtotime($date2))
{
// on each iteration, add 1 hour to previous timestamp
$next = date('Y-m-d H:i', strtotime($newdate.' +1 hour'));
$dates[] = $next;
$newdate = $next;
}
echo '<pre>';
print_r($dates);
答案 4 :(得分:0)
试试这个
$date1 = '2014-07-19 13:00';
$date2 = '2014-07-20 13:00';
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
$diff_seconds = $timestamp2 - $timestamp1;
$diff_hours = ceil($diff_seconds/3600);
for($i= 0 ; $i < $diff_hours; $i++){
$dates[] = date('Y-m-d H:i', $timestamp1 + ($i *3600));
}