4

有没有一种简单的方法可以在 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

例如。

4

5 回答 5

23
$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;
}
于 2013-08-29T14:33:48.743 回答
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;

    }
于 2014-11-24T06:45:58.420 回答
2

不知道这是否实用,但它的工作原理非常简单

$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>";
}
于 2013-08-29T14:39:54.593 回答
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));
于 2013-08-29T14:26:49.377 回答
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);
      }
于 2014-04-04T14:09:27.717 回答