我在 PHP 中有 2 个日期,如何运行 foreach 循环来完成所有这些日子? [英] I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
本文介绍了我在 PHP 中有 2 个日期,如何运行 foreach 循环来完成所有这些日子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我以日期 2010-05-01
开始,以 2010-05-10
结束.如何在 PHP 中遍历所有这些日期?
I'm starting with a date 2010-05-01
and ending with 2010-05-10
. How can I iterate through all of those dates in PHP?
推荐答案
$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s
");
}
这将输出 $start
和 $end
之间定义的时间段内的所有天数.如果要包含第 10 个,请将 $end
设置为第 11 个.您可以根据自己的喜好调整格式.请参阅 DatePeriod 的 PHP 手册.它需要 PHP 5.3.
This will output all days in the defined period between $start
and $end
. If you want to include the 10th, set $end
to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod. It requires PHP 5.3.
这篇关于我在 PHP 中有 2 个日期,如何运行 foreach 循环来完成所有这些日子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文