Php 一年中的几个月
我试图用一个循环来显示过去12个月,但三月出现了两次Php 一年中的几个月,php,Php,我试图用一个循环来显示过去12个月,但三月出现了两次 for ($i=0; $i < 12; $i++) { $month = date("d/m/Y", strtotime("now -$i month")); echo "$month<br>"; } 如何解决此问题?您可能希望用于此任务,而不是日期。它更简单、更理智 $start = new DateTime; $start->setDate($start->format('Y'), $st
for ($i=0; $i < 12; $i++) {
$month = date("d/m/Y", strtotime("now -$i month"));
echo "$month<br>";
}
如何解决此问题?您可能希望用于此任务,而不是日期。它更简单、更理智
$start = new DateTime;
$start->setDate($start->format('Y'), $start->format('n'), 1); // Normalize the day to 1
$start->sub(new DateInterval('P12M'));
$interval = new DateInterval('P1M');
$recurrences = 12;
foreach (new DatePeriod($start, $interval, $recurrences, true) as $date) {
echo $date->format('F, Y'), "\n"; // attempting to make it more clear to read here
}
输出:
30/01/2020
30/12/2019
30/11/2019
30/10/2019
30/09/2019
30/08/2019
30/07/2019
30/06/2019
30/05/2019
30/04/2019
30/03/2019
02/03/2019
February, 2019
March, 2019
April, 2019
May, 2019
June, 2019
July, 2019
August, 2019
September, 2019
October, 2019
November, 2019
December, 2019
January, 2020
您可能希望用于此任务,而不是日期。它更简单、更理智
$start = new DateTime;
$start->setDate($start->format('Y'), $start->format('n'), 1); // Normalize the day to 1
$start->sub(new DateInterval('P12M'));
$interval = new DateInterval('P1M');
$recurrences = 12;
foreach (new DatePeriod($start, $interval, $recurrences, true) as $date) {
echo $date->format('F, Y'), "\n"; // attempting to make it more clear to read here
}
输出:
30/01/2020
30/12/2019
30/11/2019
30/10/2019
30/09/2019
30/08/2019
30/07/2019
30/06/2019
30/05/2019
30/04/2019
30/03/2019
02/03/2019
February, 2019
March, 2019
April, 2019
May, 2019
June, 2019
July, 2019
August, 2019
September, 2019
October, 2019
November, 2019
December, 2019
January, 2020
在脚本中使用月的第一天作为基础
"first day of this month -$i month"
在脚本中使用月的第一天作为基础
"first day of this month -$i month"
使用DateTime并跟踪您已有的月/年组合:
$dt = new DateTime();
$previous = [];
for ($i=0; $i < 12; $i++) {
$month = $dt->format("d/m/Y");
echo "$month<br>".PHP_EOL;
$previous[$dt->format('Y-m')] = true;
$dt->modify('-1 month');
while (array_key_exists($dt->format('Y-m'), $previous)) {
$dt->modify('-1 day');
}
}
使用DateTime并跟踪您已有的月/年组合:
$dt = new DateTime();
$previous = [];
for ($i=0; $i < 12; $i++) {
$month = $dt->format("d/m/Y");
echo "$month<br>".PHP_EOL;
$previous[$dt->format('Y-m')] = true;
$dt->modify('-1 month');
while (array_key_exists($dt->format('Y-m'), $previous)) {
$dt->modify('-1 day');
}
}
二月没有第30天。你在这里期待什么?你看到三月在哪里出现两次?@Sherif,28.02+2天=>02.03。最后,也许你应该看看这个问题和答案。这对您来说可能是相同的解决方案。需要知道您的预期输出是什么,我们可以帮助您编写代码,但我们不能发明2月30日2月30日没有30日。你在这里期待什么?你看到三月在哪里出现两次?@Sherif,28.02+2天=>02.03。最后,也许你应该看看这个问题和答案。这对您来说可能是相同的解决方案。需要知道您的预期输出是什么,我们可以帮助您编写代码,但我们无法发明2月30日的版本