gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:02:32 25 4
gpt4 key购买 nike

我有两个箭头图像,一个向后递增月份,一个通过 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 仍然会导致 March 被回显。这里是否存在 2015 年 2 月……消失的错误?

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

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

最佳答案

这就是日期的工作原理,以及您遇到二月和该月的第 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');
}

关于php - 这是 PHP date() 错误,还是我的代码有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25022411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com