【问题标题】:Is this a PHP date() bug, or is there something wrong with my code?这是一个 PHP date() 错误,还是我的代码有问题?
【发布时间】:2014-09-21 05:51:44
【问题描述】:

我是箭头的两个图像,一个箭头向后增量一个,一个通过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 都是三月。

我在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");

【问题讨论】:

标签: php date datepicker


【解决方案1】:

这是日期的工作方式,以及您遇到二月和该月的第 29 天或更晚的时间。当您在该年 2 月的最后一天(即今年 2 月 28 日)之后的日期中添加一个月时,您将跳过 2 月。每当迭代几个月时,您应该始终在月初工作,以避免跳过二月。因此,如果您从 1 月 30 日开始并添加“一个月”,因为没有 2 月 30 日,您将跳到 3 月。

在不知道 2 月有多少天(或关心)的情况下,您可以通过以下方式迭代数月。我任意选择了一年后的结束日期。

$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');
}

【讨论】:

  • 啊!那是东西。非常感谢。 (人们知道一个月有多少天吗?我(显然)不知道。)
  • 不需要。如果您在迭代它们时坚持在月初工作,您将永远不会遇到这个问题。迭代后,您始终可以精确到一个月中的哪一天。
【解决方案2】:

2015 年没有 2 月 29 日。

通过一次添加或减去整个月份,您可以在请求月份的同一创建新日期。在本例中,您使 PHP 尝试将日期设为 2015 年 2 月 29 日。它自动跳到 2015 年 3 月 1 日。

如果您只关心月份,请在每个月的第一天创建日期:

date("F y", mktime(0,0,0, $month_index, 1, 2015));

幸好您正在编写此代码并在今天发现了该错误,否则您将遇到仅在每个月的 29 日(或 31 日)出现的错误(闰年除外)!

日期很难。

【讨论】:

    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 2011-05-07
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 2021-08-20
    • 1970-01-01
    相关资源
    最近更新 更多