2014-06-22 ~ 2014-06-25, 要列出這段區間的詳細日期有哪些?
- ex: 列出 2014-06-22, 2014-06-23, 2014-06-24, 2014-06-25
PHP 列出日期區間的 所有日期清單
本來要自己簡單寫寫, 後來想想這種應該很多人寫過了, 果然發現一些, 下面有兩種不錯的參考看看:
下述改寫自此篇: Generate range of dates in PHP
<?php
function date_range($first, $last, $step = '+1 day', $format = 'Y-m-d')
{
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while ($current <= $last) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
// test: print_r(date_range('2014-06-22', '2014-07-02'));
?>
PHP 版本大於 5.3.0, 可用此版本:
- 註: 需要用到 PHP: DatePeriod - Manual (PHP 5 >= 5.3.0)
- 下述改寫自此篇: datetime - PHP: Return all dates between two dates in an array
<?php
function date_range($first, $last)
{
$period = new DatePeriod(
new DateTime($first),
new DateInterval('P1D'),
new DateTime($last)
);
foreach ($period as $date)
$dates[] = $date->format('Y-m-d');
return $dates;
}
// test: print_r(date_range('2014-06-22', '2014-07-02'));
?>