【发布时间】:2010-01-11 23:36:48
【问题描述】:
我需要从当前日期开始输出未来 12 个月的日期列表(仅限周一和周二),如下所示:
2010 年 1 月
2010 年 1 月 12 日星期二
2010 年 1 月 18 日星期一
2010 年 1 月 19 日星期二
2010 年 1 月 25 日星期一
2010 年 2 月
2010 年 2 月 2 日星期二
2010 年 2 月 8 日星期一
2010 年 2 月 9 日星期二
2010 年 2 月 15 日星期一
2010 年 2 月 16 日星期二
2010 年 2 月 22 日星期一
2010 年 3 月
2010 年 3 月 9 日星期二
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 年 1 月 19 日星期二
2010 年 2 月
2010 年 2 月 8 日星期一
2010 年 2 月 2 日星期二
2010 年 2 月 15 日星期一
2010 年 2 月 9 日星期二
2010 年 2 月 22 日星期一
2010 年 2 月 16 日星期二
2010 年 3 月
2010 年 3 月 8 日星期一
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 月 13 日星期三,以测试输出。
$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 月
2010 年 2 月 9 日星期二
2010 年 2 月 8 日星期一
2010 年 2 月 16 日星期二
2010 年 2 月 15 日星期一
2010 年 2 月 23 日星期二
2010 年 2 月 22 日星期一
【问题讨论】: