是否有这样一个函数,该函数获取两个日期之间的所有日期,比如如下函数:
getDatesFromRange( \'2010-10-01\', \'2010-10-05\' );
要求输出结果为:
Array( \'2010-10-01\', \'2010-10-02\', \'2010-10-03\', \'2010-10-04\', \'2010-10-05\' )
该如何实现呢?
第一种方法:使用DatePeriod类
简单但喜欢魅力:
$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();
第二种方法:自定义函数法
function createRange($start, $end, $format = \'Y-m-d\') {
$start = new DateTime($start);
$end = new DateTime($end);
$invert = $start > $end;
$dates = array();
$dates[] = $start->format($format);
while ($start != $end) {
$start->modify(($invert ? \'-\' : \'+\') . \'1 day\');
$dates[] = $start->format($format);
}
return $dates;
}
使用示例:
print_r(createRange(\'2010-10-01\', \'2010-10-05\'));
/*Array
(
[0] => 2010-10-01
[1] => 2010-10-02
[2] => 2010-10-03
[3] => 2010-10-04
[4] => 2010-10-05
)*/
print_r(createRange(\'2010-10-05\', \'2010-10-01\', \'j M Y\'));
/*Array
(
[0] => 5 Oct 2010
[1] => 4 Oct 2010
[2] => 3 Oct 2010
[3] => 2 Oct 2010
[4] => 1 Oct 2010
)*/ 继续阅读与本文标签相同的文章
上一篇 :
开发高质量软件需要更高成本吗?
下一篇 :
盘点一下常见的对SSD的偏见与误解
-
想要使用5G网络,那么需要换手机还是换手机卡?中国移动有答案
2026-05-15栏目: 教程
-
想要体验5G网络,你需要更换手机还是手机卡?中国移动给你答案
2026-05-15栏目: 教程
-
三星Galaxy S10有一个重大的安全漏洞–但将得到修复
2026-05-15栏目: 教程
-
微信占内存太多?教你一招,让手机拥有更多空间!
2026-05-15栏目: 教程
-
中国移动重磅发布《5G新型智慧城镇白皮书》
2026-05-15栏目: 教程
