预期的输入:
getDatesFromRange( '2010-10-01', '2010-10-05' );
预期的输出:
Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )
预期的输入:
getDatesFromRange( '2010-10-01', '2010-10-05' );
预期的输出:
Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )
当前回答
public static function countDays($date1,$date2)
{
$date1 = strtotime($date1); // or your date as well
$date2 = strtotime($date2);
$datediff = $date1 - $date2;
return floor($datediff/(60*60*24));
}
public static function dateRange($date1,$date2)
{
$count = static::countDays($date1,$date2) + 1;
$dates = array();
for($i=0;$i<$count;$i++)
{
$dates[] = date("Y-m-d",strtotime($date2.'+'.$i.' days'));
}
return $dates;
}
其他回答
你必须添加$end->modify('+1 day')来包含间隔的最后一天,例如,如果不使用modify()方法,一月份将有31天而不是30天。 这个版本的代码将包括间隔的最后一天:
$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文档链接
这很简短,而且应该在PHP4+中工作。
function getDatesFromRange($start, $end){
$dates = array($start);
while(end($dates) < $end){
$dates[] = date('Y-m-d', strtotime(end($dates).' +1 day'));
}
return $dates;
}
function createDateRangeArray($start, $end) {
// Modified by JJ Geewax
$range = array();
if (is_string($start) === true) $start = strtotime($start);
if (is_string($end) === true ) $end = strtotime($end);
if ($start > $end) return createDateRangeArray($end, $start);
do {
$range[] = date('Y-m-d', $start);
$start = strtotime("+ 1 day", $start);
}
while($start < $end);
return $range;
}
来源:http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html
简单却有魅力:
$period = new DatePeriod(new DateTime('2015-01-01'), new DateInterval('P1D'), new DateTime('2015-01-15 +1 day'));
foreach ($period as $date) {
$dates[] = $date->format("Y-m-d");
}
//ONLY SHOWING
echo '<pre>';
var_dump($dates);
echo '</pre>';
exit();
使用DateTime对象的PHP 5.2解决方案。但是startDate必须在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;
}
使用:
$dates = createRange('2010-10-01', '2010-10-05');
$日期包含:
Array( '2010-10-01', '2010-10-02', '2010-10-03', '2010-10-04', '2010-10-05' )