这是一个PHP date()错误,还是我的代码有问题?

这是一个PHP date()错误,还是我的代码有问题?,php,date,datepicker,Php,Date,Datepicker,我有两个箭头图像,一个是向后递增月份,另一个是通过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 "?m

我有两个箭头图像,一个是向后递增月份,另一个是通过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>
将$month_index=6转换为$month_index=7仍然会导致3月份的情况得到回应。2015年2月的地方有没有什么bug。。。走了

更新:谢谢大家。我自己永远也找不到。我这样解决了这个问题:

$month = strtotime(date("M-01-Y") . "+".$month_index." month");

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日)(闰年除外)


日期很难确定。

这是日期的工作方式,以及你遇到二月和一个月的第29天或更晚的时间。当您在该年2月最后一天(即今年2月28日)之后的日期上添加一个月时,您将跳过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');
}

一根绳子有多长?@Fred ii-;)@无稽之谈哈哈!好的;)很高兴看到你有幽默感:)啊!就是这样。非常感谢。(人们能记住一个月有多少天吗?我(显然)不知道。)没必要。如果你坚持在月初迭代它们,你将永远不会有这个问题。您始终可以在迭代后精确到当月的某一天。
$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');
}