获取开始日期和结束日期之间的所有日期到数组中

时间:2015-03-31 01:52:14

标签: php arrays date

我无法将结果插入数组中。

这是我的代码:

$listData2="";

$end = date("n/d/Y",strtotime($row['dDate']));
$start = date("n/d/Y",strtotime($row['aDate']));

$datediff = strtotime($end) - strtotime($start);
$datediff = floor($datediff/(60*60*24));

for($i = 0; $i <=- $datediff + 1; $i++) {
    $dateArr=date("n/d/Y", strtotime($start . ' + ' . $i . 'day'));
    $listData2[]=$dateArr;
}

2 个答案:

答案 0 :(得分:1)

你有一个令人费解的方式这样做,所以我将告诉你如何将两个日期之间的所有日期变成一个数组:

$listData2 = [];
$start     = new DateTime($row['dDate']);
$end       = (new DateTime($row['aDate']))->modify('+1 day');
$interval  = DateInterval::createFromDateString('1 day');
$period    = new DatePeriod($start, $interval, $end);

foreach ($period as $dt) {
    $listData2[] =  $dt->format("n/d/Y");
}

Demo

这会初始化一个空数组以存储日期(以空字符串开头,而不是数组),并将开始日期和结束日期创建为DateTime个对象(而不是您创建的非标准字符串)然后它创建一个代表1天的DateInterval对象和一个DatePeriod对象来包装所有我们可以使用的东西。然后我们遍历DatePeriod对象并将它们添加到数组中。

(for循环中也有一个无效的运算符(<=-)。

答案 1 :(得分:0)

以下是示例代码:

$listData2 = array();
$end = date("n/d/Y",strtotime($row['dDate']));
$start = date("n/d/Y",strtotime($row['aDate']));
for(;;) {
    $listData2[]=date("n/d/Y", strtotime($start));
    $start = date("Y-m-d", strtotime("+1 day", strtotime($start)));
    if(strtotime($start)>strtotime($end)) break;
}
相关问题