我有两个箭头图像,一个是向后递增月份,另一个是通过href向前递增月份。
if (ISSET($_GET["month"])){
$month_index = $_GET["month"];
}
else{
$month_index = 0;
}
$month = strtotime("+".$month_index." month");
?>
...
<a href=<?php $month_index = $month_index - 1; echo "?month=".$month_index; ?>><img src="arrow_left.gif" ></a>
<div class="title">Logbook Calendar for <?php echo date("F Y",$month); ?> </div>
<a href=<?php $month_index = $month_index + 2; echo "?month=".$month_index; ?>><img src="arrow_right.gif"></a>
问题是,当2015年2月出现时,date()返回"2015年3月"-因此$month_index = 6和$month_index = 7都是3月。
我在http://writecodeonline.com/php/:
上运行了这段代码date_default_timezone_set("America/New_York");
$month_index = 6;
$month_index = $month_index - 1;
$month_index = $month_index + 2;
echo $month_index;
$month = strtotime("+".$month_index." month");
echo " " . $month;
echo " " . date("F Y",$month);
将$month_index=6切换到$month_index=7仍然会返回3月份。是不是有什么问题,2015年2月是…去了?
更新:谢谢大家。我一个人是找不到的。我用这种方法解决了这个问题:
$month = strtotime(date("M-01-Y") . "+".$month_index." month");
这就是日期的工作方式,当你遇到2月的第29天或更晚的时候。当您在某年2月的最后一天(即今年2月28日)之后的日期上添加一个月时,您将跳过2月。每当迭代月份时,您应该始终从月初开始工作,以避免跳过2月份。因此,如果您从1月30日开始并添加"一个月",因为没有2月30日,您将直接跳到3月。
这是你如何在不知道二月有多少天(或关心)的情况下迭代月份。我随意选了一个一年之后的结束日期。
$start = new DateTimeImmutable('@'.mktime(0, 0, 0, $month_index, 1, 2014));
$end = $start->modify('+1 year')
$interval = new DateInterval('P1M');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format('F Y');
}
2015年没有2月29日。
通过每次添加或减去整个月份,您可以在请求月份的相同天上创建新日期。在本例中,您让PHP尝试创建一个2015年2月29日的日期。自动跳转到2015年3月1日。
如果您只关心月份,则在每个月的第一天创建日期:
date("F y", mktime(0,0,0, $month_index, 1, 2015));
还好你今天写了这段代码并抓住了这个bug,否则你的bug只会在每个月的29号(或31号)出现(闰年除外)!
约会很难。