PHP: Return all dates between two dates in an arra

2018-12-31 03:20发布

Expected Input:

getDatesFromRange( '2010-10-01', '2010-10-05' );

Expected Output:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )

27条回答
后来的你喜欢了谁
2楼-- · 2018-12-31 04:07

Solution for PHP 5.2 with DateTime objects. But startDate MUST be before endDate.

function createRange($startDate, $endDate) {
    $tmpDate = new DateTime($startDate);
    $tmpEndDate = new DateTime($endDate);

    $outArray = array();
    do {
        $outArray[] = $tmpDate->format('Y-m-d');
    } while ($tmpDate->modify('+1 day') <= $tmpEndDate);

    return $outArray;
}

Using:

$dates = createRange('2010-10-01', '2010-10-05');

$dates contain:

Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )       
查看更多
谁念西风独自凉
3楼-- · 2018-12-31 04:08
function createDateRangeArray($strDateFrom,$strDateTo)
{
    // takes two dates formatted as YYYY-MM-DD and creates an
    // inclusive array of the dates between the from and to dates.

    // could test validity of dates here but I'm already doing
    // that in the main script

    $aryRange=array();

    $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     substr($strDateFrom,8,2),substr($strDateFrom,0,4));
    $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     substr($strDateTo,8,2),substr($strDateTo,0,4));

    if ($iDateTo>=$iDateFrom)
    {
        array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
        while ($iDateFrom<$iDateTo)
        {
            $iDateFrom+=86400; // add 24 hours
            array_push($aryRange,date('Y-m-d',$iDateFrom));
        }
    }
    return $aryRange;
}

source: http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html

查看更多
君临天下
4楼-- · 2018-12-31 04:10

You must add $end->modify('+1 day') to include last day of interval, for example the January will have a 31 days instead of 30 without using modify() method. This version of code will include the last day of the interval:

$begin = new DateTime( '2018-08-01' );
$end = new DateTime( '2018-08-31' );
$end = $end->modify( '+1 day' ); 

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){
    echo $date->format("Ymd") . "<br>";
}

PHP doc link

查看更多
登录 后发表回答