假設我有2個日期說2014年8月29日和2014年9月3日。我需要以下面的格式顯示日期之間的所有日期。PHP顯示一組日期之間的所有日期列表
2014年8月
29週五
30星期六
31日
2014年9月
01週一
02星期二
03週三
我知道如何打印所有日期像29,30,31,1,2,3。但我無法做到的是獲取月份名稱。
假設我有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