我试图使一个函数,将返回两个日期之间的所有日期。
我的函数是这样的:
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);
UPDATE:另外,不要对$first和$last使用d/m/Y格式,因为它不支持。不过,如果您愿意,也可以用这种格式输出。
问题是strtotime
不支持25/08/2014
格式。以下是支持的格式列表:http://ru2.php.net/manual/en/datetime.formats.date.php
你可以看到一个有效的格式是m/d/y
,所以你可以这样调用你的函数:
dateRange('08/25/2014', '08/28/2014'); // month and day swap
或
dateRange('25.08.2014', '28.08.2014'); // dots instead slashes