PHP显示一组日期之间的所有日期列表
假设我有2个日期说2014年8月29日和2014年9月3日。我需要以下面的格式显示日期之间的所有日期。PHP显示一组日期之间的所有日期列表
2014年8月
29周五
30星期六
31日
2014年9月
01周一
02星期二
03周三
我知道如何打印所有日期像29,30,31,1,2,3。但我无法做到的是获取月份名称。
相当简单的问题非常好,说实话,很基本的sollution可能..
$dateRange = new DatePeriod(
new DateTime('2014-07-28'),
new DateInterval('P1D'),
new DateTime('2014-08-04 00:00:01')
);
$month = null;
foreach ($dateRange as $date)
{
$currentMonth = $date->format('m Y');
if ($currentMonth != $month)
{
$month = $date->format('m Y');
echo $date->format('F Y').'<br />';
}
echo $date->format('d D').'<br />';
}
以上sollution结果在:
July 2014
28 Mon
29 Tue
30 Wed
31 Thu
August 2014
01 Fri
02 Sat
03 Sun
不要介意它需要PHP> = 5.3(由于使用DatePeriod),但实际的逻辑如此无论使用哪种PHP版本,您的问题都很容易实现。
把'$ date-> format('d')'改成'$ date-> format('d D')'这就完美了:) – 2014-08-28 09:12:13
我已经将你切入了追逐,你评论:) – 2014-08-28 09:14:28
@ Dennis Jamin:最后日期不会显示在你的代码中。 – Developer 2014-08-28 09:20:32
$timeS = strtotime("29 Aug 2014");
$timeE = strtotime("3 Sep 2014");
$monthS = -1;
$time = $timeS;
while ($time < $timeE) {
if ($monthS != date("n", $time)) {
echo date("M Y", $time) . "\n";
$monthS = date("n", $time);
}
echo date("d D", $time) . "\n";
$time = strtotime("+1 day", $time);
}
编辑:这件事以后,我与@hindmost评论:)
我想,这是完整的代码,如你所愿。
执行的代码是在这里...
http://phpfiddle.org/main/code/3cbe-4855
<?php
$currentMonth = null;
$timeS = strtotime("29 Aug 2013");
$timeE = strtotime("3 Sep 2014");
$time = $timeS;
while ($time < $timeE) {
$month = date("M", $time);
$year = date("Y", $time);
if ($month != $currentMonth)
echo "<br /><h3>".$month."- ".$year."</h3>";
$currentMonth = $month;
echo "<br />".date("d D", $time);
$time = strtotime("+1 day", $time);
}
?>
很简单的逻辑:'$ currentMonth = NULL; foreach(...)if($ month!= $ currentMonth)echo $ month; $ currentMonth = $ month;' – deceze 2014-08-28 08:56:49
你必须显示你已经尝试过 – hindmost 2014-08-28 09:01:09
这也是一个重复:http://stackoverflow.com/questions/12609695/php-days-between-two-dates-list – Naruto 2014-08-28 09:03:41