有没有一种简单的方法可以在PHP中获取两个日期之间的天数列表?
我想最终得到这样的东西:
(伪代码)
date1 = 29/08/2013
date2 = 03/09/2013
resultArray = functionReturnDates(date1, date2);
,结果数组将包含:
resultArray[0] = 29/08/2013
resultArray[1] = 30/08/2013
resultArray[2] = 31/08/2013
resultArray[3] = 01/09/2013
resultArray[4] = 02/09/2013
resultArray[5] = 03/09/2013
例如。
答案 0 :(得分:19)
$date1 = '29/08/2013';
$date2 = '03/09/2013';
function returnDates($fromdate, $todate) {
$fromdate = \DateTime::createFromFormat('d/m/Y', $fromdate);
$todate = \DateTime::createFromFormat('d/m/Y', $todate);
return new \DatePeriod(
$fromdate,
new \DateInterval('P1D'),
$todate->modify('+1 day')
);
}
$datePeriod = returnDates($date1, $date2);
foreach($datePeriod as $date) {
echo $date->format('d/m/Y'), PHP_EOL;
}
答案 1 :(得分:7)
function DatePeriod_start_end($begin,$end){
$begin = new DateTime($begin);
$end = new DateTime($end.' +1 day');
$daterange = new DatePeriod($begin, new DateInterval('P1D'), $end);
foreach($daterange as $date){
$dates[] = $date->format("Y-m-d");
}
return $dates;
}
答案 2 :(得分:1)
不知道这是否实用,但它非常直接
$end = '2013-08-29';
$start = '2013-08-25';
$datediff = strtotime($end) - strtotime($start);
$datediff = floor($datediff/(60*60*24));
for($i = 0; $i < $datediff + 1; $i++){
echo date("Y-m-d", strtotime($start . ' + ' . $i . 'day')) . "<br>";
}
答案 3 :(得分:0)
试试这个:
function daysBetween($start, $end)
$dates = array();
while($start <= $end)
{
array_push(
$dates,
date(
'dS M Y',
$start
)
);
$start += 86400;
}
return $dates;
}
$start = strtotime('2009-10-20');
$end = strtotime('2009-10-25');
var_dump(daysBetween($start,$end));
答案 4 :(得分:0)
$datearray = array();
$date = $date1;
$days = ceil(abs($date2 - $date1) / 86400) + 1;//no of days
for($i = 1;$i <= $days; $i++){
array_push($datearray,$date);
$date = $date+86400;
}
foreach($datearray as $days){
echo date('Y-m-d, $days);
}