我试着做一个函数,将返回两个日期之间的所有日期。
我的功能是这样的:
function dateRange($first, $last, $step = '+1 day', $format = 'd/m/Y' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
我这样称呼它:
$duration = dateRange('25/08/2014', '28/08/2014', $step = '+1 day', $format = 'd/m/Y' );
它需要像这样的数组中返回每个日期:-
array("25/08/2014", "26/08/2014", "27/08/2014", "28/08/2014");
它在这样的数组中返回错误的日期:-
Array
(
[0] => 01/01/1970
)
我怎样才能做到这一点?
我将使用DateTime和DateInterval通过以下方式实现此目的:
function dateRange($first, $last, $step='P1D', $format='d/m/Y', $timezone='Europe/London')
{
$dateObj = new DateTime($first, new DateTimeZone($timezone));
$endDateObj = new DateTime($last, new DateTimeZone($timezone));
$dateAry = array();
$dateAry[]=$dateObj->format($format);
while($dateObj->format($format) != $endDateObj->format($format)){
$dateObj->add(new DateInterval($step));
$dateAry[]=$dateObj->format($format);
}
return $dateAry;
}
$dates = dateRange('2014-08-25','2014-08-28');
print_r($dates);
更新:另外,请勿将$ first和$ last格式使用d / m / Y格式,因为它不受支持。如果需要,您可以以该格式输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句