我需要从当前日期开始输出未来 12 个月的日期列表(仅限周一和周二),如下所示:
2010 年1 月 2010 年 1 月
12 日 2010 年 1 月
18 日星期一 2010 年 1 月
19 日 星期二 2010 年 1 月
25 日 2010 年
2 月 2 日
星期二 2010 年 2 月 2 日
星期一 2010 年 2 月 8 日
星期二 2010 年 2 月 9 日
星期一 2010 年 2 月 15 日
星期二 2010 年 2 月 16 日
星期一 2010 年 2 月 22 日 星期一 2010 年3 月 2010 年
3 月
星期二2010 年 3 月
15 日星期一 2010 年 3 月
16 日星期二
...
作为 PHP 新手,我认为strtotime并在接下来的 52 周内循环是最好的方法。
$blockedDatesInput = "08 Mar 2010,12 Apr 2010"; // dont show these dates
$blockedDates = explode ("," , $blockedDatesInput); // convert to array
$currentMonth = ""; // current month marker
// loop over the next 52 weeks to find Mondays and Tuesdays
for($i=0; $i<=52; $i++){
// build the month header
$monthReference = date("M Y", strtotime('+'.$i.' Week'));
// check if date exists in $blockeddate
if (!in_array(date("d M Y", strtotime('+'.$i.' Monday')), $blockedDates) ||
!in_array(date("d M Y", strtotime('+'.$i.' Tuesday')), $blockedDates) ) {
// check if we have to show a new month
if(strcmp($monthReference, $currentMonth) <> 0){
echo $monthReference.'<br />',"\n";
}else{
// output the dates
echo date("D d M Y", strtotime('+'.$i.' Monday')).'<br />',"\n";
echo date("D d M Y", strtotime('+'.$i.' Tuesday')).'<br />',"\n";
}
$currentMonth = date("M Y", strtotime('+'.$i.' Week'));
}
}
但是我的代码的输出是
2010年 1 月 2010 年 1 月
18 日 2010 年 1 月
12 日 2010 年 1 月
25 日 2010年 2 月
19 日 2010 年
2 月8 日 2010 年 2 月
8 日 2010 年2
月 2 日 2010 年 2 月
15 日 2010 年2 月 15 日 2010 年
2 月22 日 2010 年 3 月
22 日 2010 年 2 月
16 日 2010 年
3 月
08 日
2010 年 3 月 2日星期二 2010 年 3 月
15 日星期一 2010 年 3 月9 日
星期二 2010年 3 月
22 日星期一 2010 年 3 月
16 日星期二 2010 年 3 月
29 日星期一 2010 年 3 月
23 日星期二
如您所见,日期的顺序不正确,我不知所措。
有没有更优雅/简单的方法来解决这个问题?
使用的 PHP 版本是 5.2.11,短期内没有前景 5.3 :-(
谢谢你的帮助。
按照 Aly 的建议修改以下代码。将计算机日期从 2010 年 12 月 1 日星期二更改为 2010 年 1 月 1 日星期三,以测试输出。
$blockedDatesInput = "08 Mar 2010,12 Apr 2010"; // dont show these dates
$blockedDates = explode ("," , $blockedDatesInput); // convert to array
$currentMonth = ""; // current month marker
// loop over the next 52 weeks to find Mondays and Tuesdays
for($i=0; $i<=52; $i++){
// build the month header
$monthReference = date("M Y", strtotime('+'.$i.' Week'));
// check if date exists in $blockeddate
if (!in_array(date("d M Y", strtotime('+'.$i.' Monday')), $blockedDates) ||
!in_array(date("d M Y", strtotime('+'.$i.' Tuesday')), $blockedDates) ) {
// check if we have to show a new month
if(strcmp($monthReference, $currentMonth) <> 0){
echo $monthReference.'<br />',"\n";
}else{
// output the dates (changed the order as suggested by Aly)
echo date("D d M Y", strtotime('+'.$i.' Tuesday')).'<br />',"\n";
echo date("D d M Y", strtotime('+'.$i.' Monday')).'<br />',"\n";
}
$currentMonth = date("M Y", strtotime('+'.$i.' Week'));
}
}
以错误的顺序再次输出。
2010 年 1月
周二 2010 年 1 月 19 日
周一 2010 年 1 月 18 日
周二 2010 年 1 月 26 日
周一 2010 年 1 月 25 日 2010 年
2 月 9 日
周二 2010 年 2 月 9 日
周一 2010 年 2 月 8 日
周二 2010 年 2 月 16 日
周一 2010 年 2 月 15 日
周二 2010 年 2 月 23 日 周二 2010 年 2 月
22 日周一