[英]PHP display all dates between a set of dates as list
假設我有2個日期,例如2014年8月29日和2014年9月3日。我需要以以下格式顯示這些日期之間的所有日期。
2014年8月
周五29日
30周六
31日
2014年9月
星期一01
02周二
03星期三
我知道如何打印所有日期,例如29,30,31,1,2,3。 但是我無法做到的是在兩個月份之間輸入月份名稱。
老實說,很簡單的問題,很簡單的基本解決方案。
$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 />';
}
上述解決方案導致:
July 2014
28 Mon
29 Tue
30 Wed
31 Thu
August 2014
01 Fri
02 Sat
03 Sun
請記住,它需要PHP> = 5.3(由於使用DatePeriod),但是解決您的問題的實際邏輯很容易實現,而與所使用的PHP版本無關。
$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);
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.